80 lines
1.6 KiB
Go
80 lines
1.6 KiB
Go
package security
|
|
|
|
import (
|
|
"crypto/aes"
|
|
"crypto/cipher"
|
|
"crypto/rand"
|
|
"encoding/base64"
|
|
"errors"
|
|
"io"
|
|
)
|
|
|
|
// Encryptor provides encryption/decryption for sensitive data
|
|
type Encryptor struct {
|
|
key []byte
|
|
}
|
|
|
|
// NewEncryptor creates a new encryptor with the given key
|
|
// The key must be 32 bytes for AES-256
|
|
func NewEncryptor(key string) (*Encryptor, error) {
|
|
if len(key) != 32 {
|
|
return nil, errors.New("encryption key must be 32 bytes (256 bits)")
|
|
}
|
|
return &Encryptor{
|
|
key: []byte(key),
|
|
}, nil
|
|
}
|
|
|
|
// Encrypt encrypts data using AES-256-GCM
|
|
func (e *Encryptor) Encrypt(plaintext string) (string, error) {
|
|
block, err := aes.NewCipher(e.key)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
gcm, err := cipher.NewGCM(block)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
nonce := make([]byte, gcm.NonceSize())
|
|
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
|
return "", err
|
|
}
|
|
|
|
ciphertext := gcm.Seal(nonce, nonce, []byte(plaintext), nil)
|
|
return base64.StdEncoding.EncodeToString(ciphertext), nil
|
|
}
|
|
|
|
// Decrypt decrypts data encrypted with Encrypt
|
|
func (e *Encryptor) Decrypt(ciphertext string) (string, error) {
|
|
data, err := base64.StdEncoding.DecodeString(ciphertext)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
block, err := aes.NewCipher(e.key)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
gcm, err := cipher.NewGCM(block)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
nonceSize := gcm.NonceSize()
|
|
if len(data) < nonceSize {
|
|
return "", errors.New("ciphertext too short")
|
|
}
|
|
|
|
nonce := data[:nonceSize]
|
|
ciphertextBytes := data[nonceSize:]
|
|
plaintext, err := gcm.Open(nil, nonce, ciphertextBytes, nil)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
return string(plaintext), nil
|
|
}
|