mirror of
https://github.com/navidrome/navidrome.git
synced 2024-08-30 14:26:02 +02:00
![Deluan Quintão](/assets/img/avatar_default.png)
* Encode/Encrypt passwords in DB * Only decrypts passwords if it is necessary * Add tests for encryption functions
65 lines
1.4 KiB
Go
65 lines
1.4 KiB
Go
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
|
|
}
|