mirror of
https://github.com/lordmathis/lemma.git
synced 2025-11-05 15:44:21 +00:00
Add logging to secrets package
This commit is contained in:
@@ -8,6 +8,8 @@ import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"novamd/internal/logging"
|
||||
)
|
||||
|
||||
// Service is an interface for encrypting and decrypting strings
|
||||
@@ -20,8 +22,19 @@ type encryptor struct {
|
||||
gcm cipher.AEAD
|
||||
}
|
||||
|
||||
var logger logging.Logger
|
||||
|
||||
func getLogger() logging.Logger {
|
||||
if logger == nil {
|
||||
logger = logging.WithGroup("secrets")
|
||||
}
|
||||
return logger
|
||||
}
|
||||
|
||||
// ValidateKey checks if the provided base64-encoded key is suitable for AES-256
|
||||
func ValidateKey(key string) error {
|
||||
log := getLogger()
|
||||
log.Debug("validating encryption key")
|
||||
_, err := decodeAndValidateKey(key)
|
||||
return err
|
||||
}
|
||||
@@ -53,6 +66,9 @@ func decodeAndValidateKey(key string) ([]byte, error) {
|
||||
|
||||
// NewService creates a new Encryptor instance with the provided base64-encoded key
|
||||
func NewService(key string) (Service, error) {
|
||||
log := getLogger()
|
||||
log.Debug("creating new encryption service")
|
||||
|
||||
keyBytes, err := decodeAndValidateKey(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -68,12 +84,16 @@ func NewService(key string) (Service, error) {
|
||||
return nil, fmt.Errorf("failed to create GCM: %w", err)
|
||||
}
|
||||
|
||||
log.Info("encryption service created")
|
||||
return &encryptor{gcm: gcm}, nil
|
||||
}
|
||||
|
||||
// Encrypt encrypts the plaintext using AES-256-GCM
|
||||
func (e *encryptor) Encrypt(plaintext string) (string, error) {
|
||||
log := getLogger()
|
||||
|
||||
if plaintext == "" {
|
||||
log.Debug("empty plaintext provided, returning empty string")
|
||||
return "", nil
|
||||
}
|
||||
|
||||
@@ -83,12 +103,18 @@ func (e *encryptor) Encrypt(plaintext string) (string, error) {
|
||||
}
|
||||
|
||||
ciphertext := e.gcm.Seal(nonce, nonce, []byte(plaintext), nil)
|
||||
return base64.StdEncoding.EncodeToString(ciphertext), nil
|
||||
encoded := base64.StdEncoding.EncodeToString(ciphertext)
|
||||
|
||||
log.Debug("data encrypted", "inputLength", len(plaintext), "outputLength", len(encoded))
|
||||
return encoded, nil
|
||||
}
|
||||
|
||||
// Decrypt decrypts the ciphertext using AES-256-GCM
|
||||
func (e *encryptor) Decrypt(ciphertext string) (string, error) {
|
||||
log := getLogger()
|
||||
|
||||
if ciphertext == "" {
|
||||
log.Debug("empty ciphertext provided, returning empty string")
|
||||
return "", nil
|
||||
}
|
||||
|
||||
@@ -108,5 +134,6 @@ func (e *encryptor) Decrypt(ciphertext string) (string, error) {
|
||||
return "", err
|
||||
}
|
||||
|
||||
log.Debug("data decrypted", "inputLength", len(ciphertext), "outputLength", len(plaintext))
|
||||
return string(plaintext), nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user