Bỏ qua để đến nội dung

Mẫu code AES-GCM

import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
)
// aesKeySize is the required key length for AES-256 (32 bytes).
const aesKeySize = 32
// gcmNonceSize is the standard GCM nonce length (12 bytes).
const gcmNonceSize = 12
// Encrypt encrypts plaintext with AES-256-GCM under key, using a freshly
// generated random 12-byte nonce for this call. key must be exactly 32
// bytes. The returned nonce must be stored alongside ciphertext and never
// reused with the same key.
func Encrypt(key, plaintext []byte) (ciphertext, nonce []byte, err error) {
if len(key) != aesKeySize {
return nil, nil, fmt.Errorf("crypto: encrypt: key must be %d bytes, got %d", aesKeySize, len(key))
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, nil, fmt.Errorf("crypto: encrypt: new cipher: %w", err)
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, nil, fmt.Errorf("crypto: encrypt: new GCM: %w", err)
}
nonce = make([]byte, gcmNonceSize)
if _, err := rand.Read(nonce); err != nil {
return nil, nil, fmt.Errorf("crypto: encrypt: generate nonce: %w", err)
}
ciphertext = gcm.Seal(nil, nonce, plaintext, nil)
return ciphertext, nonce, nil
}
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
)
// aesKeySize is the required key length for AES-256 (32 bytes).
const aesKeySize = 32
// gcmNonceSize is the standard GCM nonce length (12 bytes).
const gcmNonceSize = 12
// Decrypt decrypts and authenticates ciphertext with AES-256-GCM under key
// and nonce. It returns an error (rather than panicking) if key is not 32
// bytes, nonce is not 12 bytes, or authentication fails.
func Decrypt(key, nonce, ciphertext []byte) (plaintext []byte, err error) {
if len(key) != aesKeySize {
return nil, fmt.Errorf("crypto: decrypt: key must be %d bytes, got %d", aesKeySize, len(key))
}
if len(nonce) != gcmNonceSize {
return nil, fmt.Errorf("crypto: decrypt: nonce must be %d bytes, got %d", gcmNonceSize, len(nonce))
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, fmt.Errorf("crypto: decrypt: new cipher: %w", err)
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, fmt.Errorf("crypto: decrypt: new GCM: %w", err)
}
plaintext, err = gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return nil, fmt.Errorf("crypto: decrypt: authentication failed: %w", err)
}
return plaintext, nil
}