ntfy/crypto/crypto.go

44 lines
971 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-06 04:58:43 +02:00
func DeriveKey(password string, topicURL string) []byte {
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-06 04:58:43 +02:00
func Encrypt(plaintext string, key []byte) (string, error) {
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
}
jwe, err := enc.Encrypt([]byte(plaintext))
if err != nil {
return "", err
}
return jwe.CompactSerialize()
}
2022-07-06 04:58:43 +02:00
func Decrypt(input string, key []byte) (string, error) {
2022-07-05 20:15:14 +02:00
jwe, err := jose.ParseEncrypted(input)
if err != nil {
return "", err
}
out, err := jwe.Decrypt(key)
if err != nil {
return "", err
}
return string(out), nil
}