Here's a complete Go implementation for AES-GCM encryption/decryption with additional authenticated data (AAD):
go
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"io"
)
type AESGCMCrypto struct {
gcm cipher.AEAD
}
// NewAESGCMCrypto creates a new AES-GCM instance with the provided key
func NewAESGCMCrypto(key []byte) (*AESGCMCrypto, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, fmt.Errorf("failed to create cipher: %w", err)
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, fmt.Errorf("failed to create GCM: %w", err)
}
return &AESGCMCrypto{gcm: gcm}, nil
}
// Encrypt encrypts plaintext with optional additional authenticated data (AAD)
func (a *AESGCMCrypto) Encrypt(plaintext []byte, aad []byte) ([]byte, error) {
// Generate a random nonce
nonce := make([]byte, a.gcm.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return nil, fmt.Errorf("failed to generate nonce: %w", err)
}
// Encrypt the plaintext with AAD
ciphertext := a.gcm.Seal(nil, nonce, plaintext, aad)
// Prepend nonce to ciphertext for storage/transmission
result := make([]byte, len(nonce)+len(ciphertext))
copy(result[:len(nonce)], nonce)
copy(result[len(nonce):], ciphertext)
return result, nil
}
// Decrypt decrypts ciphertext with optional additional authenticated data (AAD)
func (a *AESGCMCrypto) Decrypt(data []byte, aad []byte) ([]byte, error) {
nonceSize := a.gcm.NonceSize()
if len(data) < nonceSize {
return nil, fmt.Errorf("ciphertext too short")
}
// Extract nonce and ciphertext
nonce := data[:nonceSize]
ciphertext := data[nonceSize:]
// Decrypt and verify
plaintext, err := a.gcm.Open(nil, nonce, ciphertext, aad)
if err != nil {
return nil, fmt.Errorf("decryption failed: %w", err)
}
return plaintext, nil
}
func main() {
// Example usage
key := make([]byte, 32) // 256-bit key for AES-256
if _, err := rand.Read(key); err != nil {
panic(err)
}
crypto, err := NewAESGCMCrypto(key)
if err != nil {
panic(err)
}
// Data to encrypt
plaintext := []byte("Hello, World! This is a secret message.")
// Additional authenticated data (metadata)
aad := []byte("user:john,timestamp:2025-06-28,version:1.0")
// Encrypt
encrypted, err := crypto.Encrypt(plaintext, aad)
if err != nil {
panic(err)
}
fmt.Printf("Original: %s\n", plaintext)
fmt.Printf("AAD: %s\n", aad)
fmt.Printf("Encrypted: %x\n", encrypted)
// Decrypt
decrypted, err := crypto.Decrypt(encrypted, aad)
if err != nil {
panic(err)
}
fmt.Printf("Decrypted: %s\n", decrypted)
// Demonstrate AAD verification - this will fail
wrongAAD := []byte("user:jane,timestamp:2025-06-28,version:1.0")
_, err = crypto.Decrypt(encrypted, wrongAAD)
if err != nil {
fmt.Printf("Decryption with wrong AAD failed as expected: %v\n", err)
}
}
Key features of this implementation:
AES-GCM Benefits:
Provides both confidentiality (encryption) and authenticity (authentication)
Additional Authenticated Data (AAD) is authenticated but not encrypted
Built-in protection against tampering and replay attacks
AAD Usage:
AAD can contain metadata like user IDs, timestamps, version numbers, or any contextual information
AAD is verified during decryption - if it doesn't match, decryption fails
AAD is not encrypted, so it can be stored separately if needed
Security Considerations:
Uses a random nonce for each encryption operation
Nonce is prepended to the ciphertext for convenience
Key should be 16, 24, or 32 bytes for AES-128, AES-192, or AES-256 respectively
Never reuse the same nonce with the same key
Practical Use Cases:
Database encryption with row metadata as AAD
API payload encryption with request headers as AAD
File encryption with file metadata as AAD
Message encryption with sender/recipient info as AAD
The AAD parameter ensures that even if someone has the correct key, they cannot decrypt the data without also having the exact metadata that was used during encryption.