go / expert
Snippet
Authenticated Cryptographic Encryption via AES-GCM Cipher Constructs
Standard library `crypto/cipher` provides Galois/Counter Mode (GCM) for authenticated encryption. AES-GCM guarantees both data confidentiality and cryptographic authenticity using random nonces and authentication tags.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package mainimport ("crypto/aes""crypto/cipher""crypto/rand""fmt""io")func EncryptAESGCM(key []byte, plaintext []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}return gcm.Seal(nonce, nonce, plaintext, nil), nil}func main() {key := make([]byte, 32)rand.Read(key)cipherText, _ := EncryptAESGCM(key, []byte("confidential payload"))fmt.Printf("Encrypted output byte length: %d\n", len(cipherText))}
Breakdown
1
gcm, err := cipher.NewGCM(block)
Constructs Galois/Counter Mode authenticated cipher wrapper preventing ciphertext tampering.
2
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
Populates the cryptographic nonce array with cryptographically secure random bytes from rand.Reader.
3
return gcm.Seal(nonce, nonce, plaintext, nil), nil
Encrypts payload and appends authentication tag while prefixing output buffer with unique nonce.