feat(01-foundation-03): implement AES-256-GCM encryption and Argon2id key derivation
- Encrypt/Decrypt using AES-256-GCM with random nonce prepended to ciphertext - ErrCiphertextTooShort sentinel error for malformed ciphertext - DeriveKey using Argon2id RFC 9106 params (time=1, mem=64MB, threads=4, keyLen=32) - NewSalt generates cryptographically random 16-byte salt
This commit is contained in:
52
pkg/storage/encrypt.go
Normal file
52
pkg/storage/encrypt.go
Normal file
@@ -0,0 +1,52 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"errors"
|
||||
"io"
|
||||
)
|
||||
|
||||
// ErrCiphertextTooShort is returned when ciphertext is shorter than the GCM nonce size.
|
||||
var ErrCiphertextTooShort = errors.New("ciphertext too short")
|
||||
|
||||
// Encrypt encrypts plaintext using AES-256-GCM with a random nonce.
|
||||
// The nonce is prepended to the returned ciphertext.
|
||||
// key must be exactly 32 bytes (AES-256).
|
||||
func Encrypt(plaintext []byte, key []byte) ([]byte, error) {
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
nonce := make([]byte, gcm.NonceSize())
|
||||
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Seal appends encrypted data to nonce, so nonce is prepended
|
||||
ciphertext := gcm.Seal(nonce, nonce, plaintext, nil)
|
||||
return ciphertext, nil
|
||||
}
|
||||
|
||||
// Decrypt decrypts ciphertext produced by Encrypt.
|
||||
// Expects the nonce to be prepended to the ciphertext.
|
||||
func Decrypt(ciphertext []byte, key []byte) ([]byte, error) {
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
nonceSize := gcm.NonceSize()
|
||||
if len(ciphertext) < nonceSize {
|
||||
return nil, ErrCiphertextTooShort
|
||||
}
|
||||
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
|
||||
return gcm.Open(nil, nonce, ciphertext, nil)
|
||||
}
|
||||
Reference in New Issue
Block a user