1
0
Fork 0
mirror of https://github.com/binwiederhier/ntfy.git synced 2024-11-01 09:31:18 +01:00
ntfy/crypto/crypto.go
Philipp Heckel cae06c5c61 Continued
2022-07-13 20:31:17 -04:00

43 lines
960 B
Go

package crypto
import (
"crypto/sha256"
"golang.org/x/crypto/pbkdf2"
"gopkg.in/square/go-jose.v2"
)
const (
jweEncryption = jose.A256GCM
jweAlgorithm = jose.DIRECT
keyLenBytes = 32 // 256-bit for AES-256
keyDerivIter = 50000
)
func DeriveKey(password, topicURL string) []byte {
salt := sha256.Sum256([]byte(topicURL))
return pbkdf2.Key([]byte(password), salt[:], keyDerivIter, keyLenBytes, sha256.New)
}
func Encrypt(plaintext []byte, key []byte) (string, error) {
enc, err := jose.NewEncrypter(jweEncryption, jose.Recipient{Algorithm: jweAlgorithm, Key: key}, nil)
if err != nil {
return "", err
}
jwe, err := enc.Encrypt(plaintext)
if err != nil {
return "", err
}
return jwe.CompactSerialize()
}
func Decrypt(ciphertext string, key []byte) ([]byte, error) {
jwe, err := jose.ParseEncrypted(ciphertext)
if err != nil {
return nil, err
}
out, err := jwe.Decrypt(key)
if err != nil {
return nil, err
}
return out, nil
}