Encrypt passwords in DB (#1187)

* Encode/Encrypt passwords in DB

* Only decrypts passwords if it is necessary

* Add tests for encryption functions
This commit is contained in:
Deluan Quintão
2021-06-18 18:38:38 -04:00
committed by GitHub
parent d42dfafad4
commit 66b74c81f1
12 changed files with 302 additions and 7 deletions
+64
View File
@@ -0,0 +1,64 @@
package utils
import (
"context"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"io"
"github.com/navidrome/navidrome/log"
)
func Encrypt(ctx context.Context, encKey []byte, data string) (string, error) {
plaintext := []byte(data)
block, err := aes.NewCipher(encKey)
if err != nil {
log.Error(ctx, "Could not create a cipher", err)
return "", err
}
aesGCM, err := cipher.NewGCM(block)
if err != nil {
log.Error(ctx, "Could not create a GCM", "user", err)
return "", err
}
nonce := make([]byte, aesGCM.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
log.Error(ctx, "Could generate nonce", err)
return "", err
}
ciphertext := aesGCM.Seal(nonce, nonce, plaintext, nil)
return base64.StdEncoding.EncodeToString(ciphertext), nil
}
func Decrypt(ctx context.Context, encKey []byte, encData string) (string, error) {
enc, _ := base64.StdEncoding.DecodeString(encData)
block, err := aes.NewCipher(encKey)
if err != nil {
log.Error(ctx, "Could not create a cipher", err)
return "", err
}
aesGCM, err := cipher.NewGCM(block)
if err != nil {
log.Error(ctx, "Could not create a GCM", err)
return "", err
}
nonceSize := aesGCM.NonceSize()
nonce, ciphertext := enc[:nonceSize], enc[nonceSize:]
plaintext, err := aesGCM.Open(nil, nonce, ciphertext, nil)
if err != nil {
log.Error(ctx, "Could not decrypt password", err)
return "", err
}
return string(plaintext), nil
}
+38
View File
@@ -0,0 +1,38 @@
package utils
import (
"context"
"crypto/sha256"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("encrypt", func() {
It("decrypts correctly when using the same encryption key", func() {
sum := sha256.Sum256([]byte("password"))
encKey := sum[0:]
data := "Can you keep a secret?"
encrypted, err := Encrypt(context.Background(), encKey, data)
Expect(err).ToNot(HaveOccurred())
decrypted, err := Decrypt(context.Background(), encKey, encrypted)
Expect(err).ToNot(HaveOccurred())
Expect(decrypted).To(Equal(data))
})
It("fails to decrypt if not using the same encryption key", func() {
sum := sha256.Sum256([]byte("password"))
encKey := sum[0:]
data := "Can you keep a secret?"
encrypted, err := Encrypt(context.Background(), encKey, data)
Expect(err).ToNot(HaveOccurred())
sum = sha256.Sum256([]byte("different password"))
encKey = sum[0:]
_, err = Decrypt(context.Background(), encKey, encrypted)
Expect(err).To(MatchError("cipher: message authentication failed"))
})
})