1
0
Fork 0
mirror of https://github.com/binwiederhier/ntfy.git synced 2024-11-24 04:09:13 +01:00
ntfy/crypto/crypto.go

44 lines
960 B
Go
Raw Normal View History

2022-07-01 21:48:49 +02:00
package crypto
import (
2022-07-06 04:58:43 +02:00
"crypto/sha256"
"golang.org/x/crypto/pbkdf2"
"gopkg.in/square/go-jose.v2"
2022-07-01 21:48:49 +02:00
)
const (
2022-07-06 04:58:43 +02:00
jweEncryption = jose.A256GCM
jweAlgorithm = jose.DIRECT
keyLenBytes = 32 // 256-bit for AES-256
keyDerivIter = 50000
2022-07-01 21:48:49 +02:00
)
2022-07-14 02:31:17 +02:00
func DeriveKey(password, topicURL string) []byte {
2022-07-06 04:58:43 +02:00
salt := sha256.Sum256([]byte(topicURL))
return pbkdf2.Key([]byte(password), salt[:], keyDerivIter, keyLenBytes, sha256.New)
2022-07-01 21:48:49 +02:00
}
2022-07-14 02:31:17 +02:00
func Encrypt(plaintext []byte, key []byte) (string, error) {
2022-07-06 04:58:43 +02:00
enc, err := jose.NewEncrypter(jweEncryption, jose.Recipient{Algorithm: jweAlgorithm, Key: key}, nil)
2022-07-05 20:15:14 +02:00
if err != nil {
return "", err
}
2022-07-14 02:31:17 +02:00
jwe, err := enc.Encrypt(plaintext)
2022-07-05 20:15:14 +02:00
if err != nil {
return "", err
}
return jwe.CompactSerialize()
}
2022-07-14 02:31:17 +02:00
func Decrypt(ciphertext string, key []byte) ([]byte, error) {
jwe, err := jose.ParseEncrypted(ciphertext)
2022-07-05 20:15:14 +02:00
if err != nil {
2022-07-14 02:31:17 +02:00
return nil, err
2022-07-05 20:15:14 +02:00
}
out, err := jwe.Decrypt(key)
if err != nil {
2022-07-14 02:31:17 +02:00
return nil, err
2022-07-05 20:15:14 +02:00
}
2022-07-14 02:31:17 +02:00
return out, nil
2022-07-05 20:15:14 +02:00
}