Continued

This commit is contained in:
Philipp Heckel 2022-07-13 20:31:17 -04:00
parent 78f9d4835e
commit cae06c5c61
7 changed files with 78 additions and 15 deletions

View file

@ -13,31 +13,31 @@ const (
keyDerivIter = 50000
)
func DeriveKey(password string, topicURL string) []byte {
func DeriveKey(password, topicURL string) []byte {
salt := sha256.Sum256([]byte(topicURL))
return pbkdf2.Key([]byte(password), salt[:], keyDerivIter, keyLenBytes, sha256.New)
}
func Encrypt(plaintext string, key []byte) (string, error) {
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([]byte(plaintext))
jwe, err := enc.Encrypt(plaintext)
if err != nil {
return "", err
}
return jwe.CompactSerialize()
}
func Decrypt(input string, key []byte) (string, error) {
jwe, err := jose.ParseEncrypted(input)
func Decrypt(ciphertext string, key []byte) ([]byte, error) {
jwe, err := jose.ParseEncrypted(ciphertext)
if err != nil {
return "", err
return nil, err
}
out, err := jwe.Decrypt(key)
if err != nil {
return "", err
return nil, err
}
return string(out), nil
return out, nil
}

View file

@ -1,25 +1,32 @@
package crypto
import (
"fmt"
"github.com/stretchr/testify/require"
"testing"
)
func TestDeriveKey(t *testing.T) {
key := DeriveKey("secr3t password", "https://ntfy.sh/mysecret")
require.Equal(t, "30b7e72f6273da6e59d2dec535466e548da3eafc98650c9664c06edab707fa25", fmt.Sprintf("%x", key))
}
func TestEncryptDecrypt(t *testing.T) {
message := "this is a message or is it?"
ciphertext, err := Encrypt(message, []byte("AES256Key-32Characters1234567890"))
ciphertext, err := Encrypt([]byte(message), []byte("AES256Key-32Characters1234567890"))
require.Nil(t, err)
plaintext, err := Decrypt(ciphertext, []byte("AES256Key-32Characters1234567890"))
require.Nil(t, err)
require.Equal(t, message, plaintext)
require.Equal(t, message, string(plaintext))
}
func TestEncryptDecrypt_FromPHP(t *testing.T) {
ciphertext := "eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0..vbe1Qv_-mKYbUgce.EfmOUIUi7lxXZG_o4bqXZ9pmpr1Rzs4Y5QLE2XD2_aw_SQ.y2hadrN5b2LEw7_PJHhbcA"
key := DeriveKey("secr3t password", "https://ntfy.sh/mysecret")
fmt.Printf("%x", key)
plaintext, err := Decrypt(ciphertext, key)
require.Nil(t, err)
require.Equal(t, `{"message":"Secret!","priority":5}`, plaintext)
require.Equal(t, `{"message":"Secret!","priority":5}`, string(plaintext))
}
func TestEncryptDecrypt_FromPython(t *testing.T) {
@ -27,5 +34,5 @@ func TestEncryptDecrypt_FromPython(t *testing.T) {
key := DeriveKey("secr3t password", "https://ntfy.sh/mysecret")
plaintext, err := Decrypt(ciphertext, key)
require.Nil(t, err)
require.Equal(t, `{"message":"Python says hi","tags":["secret"]}`, plaintext)
require.Equal(t, `{"message":"Python says hi","tags":["secret"]}`, string(plaintext))
}