Skip to content
TheChatArchiveThe Chat Archive
Claudeclaude-opus-4-20250514-thinking-16k· AnthropicHugging Face LMArena Human Preference 140K

GoLang AES GCM encrypt/decrypt with add metadata

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-sonnet-4-20250514’s answer.
  1. User

    GoLang AES GCM encrypt/decrypt with add metadata

  2. Claude Assistant

    Here's a complete example of AES-GCM encryption and decryption in Go with additional authenticated data (AAD):

    package main
    
    import (
        "crypto/aes"
        "crypto/cipher"
        "crypto/rand"
        "encoding/base64"
        "fmt"
        "io"
    )
    
    // encrypt performs AES-GCM encryption with additional authenticated data
    func encrypt(plaintext []byte, key []byte, additionalData []byte) ([]byte, []byte, error) {
        // Create cipher block
        block, err := aes.NewCipher(key)
        if err != nil {
            return nil, nil, err
        }
    
        // Create GCM mode
        aesGCM, err := cipher.NewGCM(block)
        if err != nil {
            return nil, nil, err
        }
    
        // Generate nonce
        nonce := make([]byte, aesGCM.NonceSize())
        if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
            return nil, nil, err
        }
    
        // Encrypt and authenticate
        ciphertext := aesGCM.Seal(nil, nonce, plaintext, additionalData)
    
        return ciphertext, nonce, nil
    }
    
    // decrypt performs AES-GCM decryption and verifies additional authenticated data
    func decrypt(ciphertext []byte, key []byte, nonce []byte, additionalData []byte) ([]byte, error) {
        // Create cipher block
        block, err := aes.NewCipher(key)
        if err != nil {
            return nil, err
        }
    
        // Create GCM mode
        aesGCM, err := cipher.NewGCM(block)
        if err != nil {
            return nil, err
        }
    
        // Decrypt and verify
        plaintext, err := aesGCM.Open(nil, nonce, ciphertext, additionalData)
        if err != nil {
            return nil, err
        }
    
        return plaintext, nil
    }
    
    func main() {
        // Example usage
        key := make([]byte, 32) // AES-256
        if _, err := rand.Read(key); err != nil {
            panic(err)
        }
    
        // Data to encrypt
        message := []byte("This is a secret message")
        metadata := []byte("user_id=12345,timestamp=1234567890")
    
        fmt.Println("Original message:", string(message))
        fmt.Println("Additional data:", string(metadata))
    
        // Encrypt
        ciphertext, nonce, err := encrypt(message, key, metadata)
        if err != nil {
            panic(err)
        }
    
        fmt.Printf("\nCiphertext (base64): %s\n", base64.StdEncoding.EncodeToString(ciphertext))
        fmt.Printf("Nonce (base64): %s\n", base64.StdEncoding.EncodeToString(nonce))
    
        // Decrypt
        decrypted, err := decrypt(ciphertext, key, nonce, metadata)
        if err != nil {
            panic(err)
        }
    
        fmt.Println("\nDecrypted message:", string(decrypted))
    
        // Demonstrate authentication failure with wrong metadata
        wrongMetadata := []byte("user_id=99999,timestamp=1234567890")
        _, err = decrypt(ciphertext, key, nonce, wrongMetadata)
        if err != nil {
            fmt.Println("\nAuthentication failed with wrong metadata:", err)
        }
    }
    

    For production use, here's a more complete implementation with better structure:

    package main
    
    import (
        "crypto/aes"
        "crypto/cipher"
        "crypto/rand"
        "encoding/json"
        "errors"
        "io"
    )
    
    // EncryptedData contains all components needed for decryption
    type EncryptedData struct {
        Ciphertext []byte `json:"ciphertext"`
        Nonce      []byte `json:"nonce"`
    }
    
    // AESGCMCrypto handles AES-GCM encryption operations
    type AESGCMCrypto struct {
        key []byte
    }
    
    // NewAESGCMCrypto creates a new AES-GCM crypto instance
    func NewAESGCMCrypto(key []byte) (*AESGCMCrypto, error) {
        if len(key) != 16 && len(key) != 24 && len(key) != 32 {
            return nil, errors.New("key must be 16, 24, or 32 bytes")
        }
        return &AESGCMCrypto{key: key}, nil
    }
    
    // EncryptWithMetadata encrypts data with additional authenticated data
    func (c *AESGCMCrypto) EncryptWithMetadata(plaintext []byte, metadata map[string]string) (*EncryptedData, error) {
        // Serialize metadata
        metadataBytes, err := json.Marshal(metadata)
        if err != nil {
            return nil, err
        }
    
        block, err := aes.NewCipher(c.key)
        if err != nil {
            return nil, err
        }
    
        aesGCM, err := cipher.NewGCM(block)
        if err != nil {
            return nil, err
        }
    
        nonce := make([]byte, aesGCM.NonceSize())
        if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
            return nil, err
        }
    
        ciphertext := aesGCM.Seal(nil, nonce, plaintext, metadataBytes)
    
        return &EncryptedData{
            Ciphertext: ciphertext,
            Nonce:      nonce,
        }, nil
    }
    
    // DecryptWithMetadata decrypts data and verifies additional authenticated data
    func (c *AESGCMCrypto) DecryptWithMetadata(data *EncryptedData, metadata map[string]string) ([]byte, error) {
        // Serialize metadata
        metadataBytes, err := json.Marshal(metadata)
        if err != nil {
            return nil, err
        }
    
        block, err := aes.NewCipher(c.key)
        if err != nil {
            return nil, err
        }
    
        aesGCM, err := cipher.NewGCM(block)
        if err != nil {
            return nil, err
        }
    
        plaintext, err := aesGCM.Open(nil, data.Nonce, data.Ciphertext, metadataBytes)
        if err != nil {
            return nil, err
        }
    
        return plaintext, nil
    }
    
    // GenerateKey generates a random AES key
    func GenerateKey(size int) ([]byte, error) {
        if size != 16 && size != 24 && size != 32 {
            return nil, errors.New("key size must be 16, 24, or 32 bytes")
        }
        key := make([]byte, size)
        if _, err := rand.Read(key); err != nil {
            return nil, err
        }
        return key, nil
    }
    
    func main() {
        // Generate a key
        key, err := GenerateKey(32) // AES-256
        if err != nil {
            panic(err)
        }
    
        // Create crypto instance
        crypto, err := NewAESGCMCrypto(key)
        if err != nil {
            panic(err)
        }
    
        // Example metadata
        metadata := map[string]string{
            "user_id":   "12345",
            "timestamp": "2024-01-15T10:30:00Z",
            "action":    "document_upload",
        }
    
        // Encrypt
        message := []byte("Sensitive document content")
        encrypted, err := crypto.EncryptWithMetadata(message, metadata)
        if err != nil {
            panic(err)
        }
    
        fmt.Println("Encryption successful")
    
        // Decrypt with correct metadata
        decrypted, err := crypto.DecryptWithMetadata(encrypted, metadata)
        if err != nil {
            panic(err)
        }
        fmt.Printf("Decrypted: %s\n", decrypted)
    
        // Try with modified metadata (will fail)
        wrongMetadata := map[string]string{
            "user_id":   "99999", // Different user
            "timestamp": "2024-01-15T10:30:00Z",
            "action":    "document_upload",
        }
        
        _, err = crypto.DecryptWithMetadata(encrypted, wrongMetadata)
        if err != nil {
            fmt.Println("Authentication failed with wrong metadata (expected)")
        }
    }
    

    The AES-GCM mode provides authenticated encryption, meaning it encrypts the data and also creates an authentication tag that verifies both the ciphertext and any additional authenticated data (AAD) haven't been tampered with. The additional authenticated data is not encrypted but is authenticated, making it perfect for metadata that needs to be readable but tamper-proof.

    Key points about this implementation: The nonce must be unique for each encryption operation with the same key, which is why we generate it randomly each time. The additional authenticated data must be exactly the same during decryption as it was during encryption, or the authentication will fail. The authentication tag is automatically appended to the ciphertext by the Seal method and verified by the Open method. For production systems, you should securely store and manage the encryption keys, possibly using a key management service.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.