qcc/internal/crypto/atrest.go
2026-06-30 12:52:09 +03:00

43 lines
1.1 KiB
Go

package crypto
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"io"
)
func EncryptRecord(plaintext []byte, key [32]byte) (nonce [12]byte, ciphertext []byte, authTag []byte, err error) {
block, err := aes.NewCipher(key[:])
if err != nil {
return nonce, nil, nil, err
}
aead, err := cipher.NewGCM(block)
if err != nil {
return nonce, nil, nil, err
}
_, err = io.ReadFull(rand.Reader, nonce[:])
if err != nil {
return nonce, nil, nil, err
}
sealed := aead.Seal(nil, nonce[:], plaintext, nil)
tagStart := len(sealed) - aead.Overhead()
ciphertext = sealed[:tagStart]
authTag = sealed[tagStart:]
return nonce, ciphertext, authTag, nil
}
func DecryptRecord(ciphertext []byte, nonce [12]byte, authTag []byte, key [32]byte) ([]byte, error) {
block, err := aes.NewCipher(key[:])
if err != nil {
return nil, err
}
aead, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
sealed := make([]byte, len(ciphertext)+len(authTag))
copy(sealed, ciphertext)
copy(sealed[len(ciphertext):], authTag)
return aead.Open(nil, nonce[:], sealed, nil)
}