Skip to content

AES-GCM

Header: #include <cryptopp/aes.h> and #include <cryptopp/gcm.h>
Namespace: CryptoPP Since: Crypto++ 3.1 (AES, as Rijndael), 5.6.0 (GCM mode) [1]

AES-GCM (Advanced Encryption Standard in Galois/Counter Mode) is an authenticated encryption algorithm that provides both confidentiality and authenticity. GCM is specified in NIST SP 800-38D [2]. It is used in TLS 1.3 cipher suites [3] and in IPsec ESP [4].

Quick Example

#include <cryptopp/aes.h>
#include <cryptopp/gcm.h>
#include <cryptopp/filters.h>
#include <cryptopp/hex.h>
#include <iostream>

int main() {
    using namespace CryptoPP;

    // Key and IV (in real code, generate randomly)
    byte key[AES::DEFAULT_KEYLENGTH] = {0}; // 16 bytes for AES-128
    byte iv[12] = {0};  // 12 bytes recommended for GCM

    // Message to encrypt
    std::string plaintext = "Hello, World!";
    std::string ciphertext, decrypted;

    // Encrypt
    GCM<AES>::Encryption enc;
    enc.SetKeyWithIV(key, sizeof(key), iv, sizeof(iv));

    StringSource(plaintext, true,
        new AuthenticatedEncryptionFilter(enc,
            new StringSink(ciphertext)
        )
    );

    // Decrypt
    GCM<AES>::Decryption dec;
    dec.SetKeyWithIV(key, sizeof(key), iv, sizeof(iv));

    StringSource(ciphertext, true,
        new AuthenticatedDecryptionFilter(dec,
            new StringSink(decrypted)
        )
    );

    std::cout << "Decrypted: " << decrypted << std::endl;
    return 0;
}

Usage Guidelines

Do:

  • Use AES-GCM for authenticated encryption (encryption + integrity)
  • Use 12-byte IVs, the length NIST recommends
  • Build IVs from a counter, or generate them randomly and stop at 2^32 encryptions per key
  • Never reuse an IV with the same key [2]

Avoid:

  • Using ECB or CBC mode without authentication (use GCM instead)
  • Hardcoded keys or IVs (shown in examples for clarity only)
  • Reusing IVs - each encryption must use a unique IV
  • Ignoring authentication failures during decryption

We recommend 256-bit keys (AES-256-GCM) for new systems. See Security Levels for what the key sizes mean.

Class: GCM

Template class for AES in GCM (Galois/Counter Mode) authenticated encryption.

Key Sizes

Key SizeConstantRecommended
128-bitAES::DEFAULT_KEYLENGTH (16)Acceptable
192-bit24 bytesRare
256-bitAES::MAX_KEYLENGTH (32)✓ Recommended

AES is defined for 128-, 192- and 256-bit keys [5], and the library’s AES accepts 16, 24 or 32 bytes [6].

Constants

Key size:  16, 24, or 32 bytes (128/192/256-bit)
IV size:   12 bytes recommended (96-bit)
Tag size:  16 bytes (128-bit)
Block size: 16 bytes (128-bit, fixed)

IVSize() returns 12, the IV may be 1 to UINT_MAX bytes, and the full tag is 16 bytes [7].

GCM::Encryption

Authenticated encryption class.

Methods

SetKeyWithIV()

void SetKeyWithIV(const byte* key, size_t keyLength,
                  const byte* iv, size_t ivLength);

Set encryption key and initialization vector.

Parameters:

  • key - Encryption key (16, 24, or 32 bytes)
  • keyLength - Length of key in bytes
  • iv - Initialization vector (12 bytes recommended)
  • ivLength - Length of IV in bytes

Thread Safety: Not thread-safe. Create separate objects per thread.

Example:

GCM<AES>::Encryption enc;
byte key[32];  // 256-bit key
byte iv[12];   // 96-bit IV

AutoSeededRandomPool rng;
rng.GenerateBlock(key, sizeof(key));
rng.GenerateBlock(iv, sizeof(iv));

enc.SetKeyWithIV(key, sizeof(key), iv, sizeof(iv));

SpecifyDataLengths()

void SpecifyDataLengths(lword headerLength, lword messageLength,
                        lword footerLength = 0);

Specify lengths of additional authenticated data (AAD) and message.

Parameters:

  • headerLength - Length of AAD in bytes
  • messageLength - Length of plaintext in bytes
  • footerLength - Length of footer (usually 0)

Optional for GCM: GCM does not need the lengths in advance, so NeedsPrespecifiedDataLengths() is false. When called, the function checks the lengths against MaxHeaderLength() and MaxMessageLength() and throws InvalidArgument if they are too long [8].

EncryptAndAuthenticate()

void EncryptAndAuthenticate(byte* ciphertext, byte* mac, size_t macSize,
                            const byte* iv, int ivLength,
                            const byte* aad, size_t aadLength,
                            const byte* message, size_t messageLength);

One-shot encryption with authentication.

Parameters:

  • ciphertext - Output buffer (same size as message)
  • mac - Output authentication tag (16 bytes)
  • macSize - Size of MAC buffer (usually 16)
  • iv - Initialization vector
  • ivLength - IV length (12 bytes recommended)
  • aad - Additional authenticated data (can be NULL)
  • aadLength - AAD length
  • message - Plaintext to encrypt
  • messageLength - Plaintext length

Throws: InvalidArgument if macSize is 0 or larger than 16, if the IV length is out of range, or if the AAD or message is longer than the maximum [8][9]

Example:

GCM<AES>::Encryption enc;
enc.SetKeyWithIV(key, sizeof(key), iv, sizeof(iv));

byte ciphertext[100];
byte tag[16];
std::string plaintext = "Secret message";

enc.EncryptAndAuthenticate(
    ciphertext, tag, sizeof(tag),
    iv, sizeof(iv),
    nullptr, 0,  // No AAD
    (const byte*)plaintext.data(), plaintext.size()
);

GCM::Decryption

Authenticated decryption class.

Methods

SetKeyWithIV()

void SetKeyWithIV(const byte* key, size_t keyLength,
                  const byte* iv, size_t ivLength);

Set decryption key and IV (same as encryption).

DecryptAndVerify()

bool DecryptAndVerify(byte* message,
                      const byte* mac, size_t macSize,
                      const byte* iv, int ivLength,
                      const byte* aad, size_t aadLength,
                      const byte* ciphertext, size_t ciphertextLength);

One-shot decryption with authentication verification.

Parameters:

  • message - Output buffer for plaintext
  • mac - Authentication tag to verify (16 bytes)
  • macSize - Size of MAC (usually 16)
  • iv - Initialization vector (must match encryption)
  • ivLength - IV length
  • aad - Additional authenticated data (must match encryption)
  • aadLength - AAD length
  • ciphertext - Encrypted data
  • ciphertextLength - Ciphertext length

Returns: true if authentication succeeded, false if verification failed [10]

Important: Always check the return value. If false, the message has been tampered with.

Example:

GCM<AES>::Decryption dec;
dec.SetKeyWithIV(key, sizeof(key), iv, sizeof(iv));

byte plaintext[100];
bool valid = dec.DecryptAndVerify(
    plaintext,
    tag, sizeof(tag),
    iv, sizeof(iv),
    nullptr, 0,  // No AAD
    ciphertext, ciphertextLength
);

if (!valid) {
    std::cerr << "Authentication failed! Message tampered." << std::endl;
    return 1;
}

Complete Example: File Encryption

AuthenticatedDecryptionFilter forwards decrypted data to its attachment before it checks the tag [11], so the decryption below collects the plaintext in memory and writes the file only after verification succeeds.

#include <cryptopp/aes.h>
#include <cryptopp/gcm.h>
#include <cryptopp/files.h>
#include <cryptopp/filters.h>
#include <cryptopp/osrng.h>
#include <cryptopp/secblock.h>
#include <iostream>
#include <fstream>

using namespace CryptoPP;

void encryptFile(const std::string& filename, const SecByteBlock& key) {
    // Generate random IV
    AutoSeededRandomPool rng;
    byte iv[12];
    rng.GenerateBlock(iv, sizeof(iv));

    // Read file
    std::string plaintext;
    FileSource(filename.c_str(), true, new StringSink(plaintext));

    // Encrypt
    std::string ciphertext;
    GCM<AES>::Encryption enc;
    enc.SetKeyWithIV(key, key.size(), iv, sizeof(iv));

    AuthenticatedEncryptionFilter aef(enc,
        new StringSink(ciphertext)
    );
    aef.Put((const byte*)plaintext.data(), plaintext.size());
    aef.MessageEnd();

    // Save: IV + ciphertext + tag (tag is appended automatically)
    std::ofstream out(filename + ".enc", std::ios::binary);
    out.write((const char*)iv, sizeof(iv));
    out.write(ciphertext.data(), ciphertext.size());
}

bool decryptFile(const std::string& inName, const std::string& outName,
                 const SecByteBlock& key) {
    // Read encrypted file
    std::ifstream in(inName, std::ios::binary);

    // Read IV
    byte iv[12];
    if (!in.read(reinterpret_cast<char*>(iv), sizeof(iv)))
        return false;  // file too short to hold the IV

    // Read ciphertext + tag
    std::string ciphertext;
    FileSource(in, true, new StringSink(ciphertext));

    // Decrypt and verify into memory
    try {
        std::string plaintext;
        GCM<AES>::Decryption dec;
        dec.SetKeyWithIV(key, key.size(), iv, sizeof(iv));

        AuthenticatedDecryptionFilter adf(dec,
            new StringSink(plaintext),
            AuthenticatedDecryptionFilter::DEFAULT_FLAGS
        );

        StringSource(ciphertext, true,
            new Redirector(adf)
        );

        // Tag verified: only now write the output file
        FileSink(outName.c_str()).Put((const byte*)plaintext.data(),
                                      plaintext.size());
        return true;

    } catch (const HashVerificationFilter::HashVerificationFailed& e) {
        std::cerr << "Authentication failed: " << e.what() << std::endl;
        return false;
    }
}

int main() {
    // Generate 256-bit key
    AutoSeededRandomPool rng;
    SecByteBlock key(AES::MAX_KEYLENGTH);
    rng.GenerateBlock(key, key.size());

    // Encrypt
    encryptFile("document.txt", key);
    std::cout << "File encrypted successfully" << std::endl;

    // Decrypt
    if (decryptFile("document.txt.enc", "document.dec.txt", key)) {
        std::cout << "File decrypted successfully" << std::endl;
    }

    return 0;
}

Additional Authenticated Data (AAD)

AAD is data that’s authenticated but not encrypted (like packet headers) [2].

#include <cryptopp/aes.h>
#include <cryptopp/gcm.h>
#include <cryptopp/filters.h>

void encryptWithAAD() {
    using namespace CryptoPP;

    byte key[32], iv[12];
    // ... initialize key and iv ...

    std::string header = "packet-id:12345";  // AAD (not encrypted)
    std::string plaintext = "Secret payload";
    std::string ciphertext;

    GCM<AES>::Encryption enc;
    enc.SetKeyWithIV(key, sizeof(key), iv, sizeof(iv));

    // Add AAD before plaintext
    AuthenticatedEncryptionFilter aef(enc,
        new StringSink(ciphertext)
    );

    aef.ChannelPut(AAD_CHANNEL, (const byte*)header.data(), header.size());
    aef.ChannelMessageEnd(AAD_CHANNEL);

    aef.ChannelPut(DEFAULT_CHANNEL, (const byte*)plaintext.data(),
                   plaintext.size());
    aef.ChannelMessageEnd(DEFAULT_CHANNEL);

    // Now ciphertext contains: encrypted payload + tag
    // Header remains in plaintext but is authenticated
}

Performance

NIST describes both GCM functions as relatively efficient and parallelizable [2]. AlgorithmProvider() on a GCM object reports the provider of the underlying AES implementation [7], which tells you whether a hardware path such as AES-NI is in use.

Security

Quick Summary

AspectRecommendationSource
Key sizeAES-128, AES-192 or AES-256FIPS 197 [5]
IV / nonce12-byte IV, never repeated under a keySP 800-38D [2]
Random IVsAt most 2^32 encryptions per keySP 800-38D section 8.3 [2]
Tag length16 bytes; 12 to 16 bytes generally allowedSP 800-38D section 5.2.1.2 [2]
Data per keyNIST suggests at most 2^64 blocks of plaintext and AADSP 800-38D appendix B [2]

Practical rules of thumb:

  • Either build the IV from a fixed field and a counter, or generate it randomly; SP 800-38D describes both constructions.
  • With random IVs, stop at 2^32 encryptions under one key.
  • Always use and verify the authentication tag; treat any verification failure as a hard error and discard the output.
  • Prefer a 128-bit tag. A forger’s chance of success grows with message length and shrinks with tag length, so short tags need the extra limits in SP 800-38D appendix C [2].
Detailed Security Properties

Security Bounds

PropertyValueSource
Tag guessA random t-bit tag is correct with probability 1/2^tSP 800-38D appendix B [2]
Targeted forgeryAbout n/2^t, where n is the number of blocks of ciphertext and AADSP 800-38D appendix B [2]
IV uniquenessProbability of any repeated IV under a key no greater than 2^-32SP 800-38D section 8 [2]
Random IVsAt most 2^32 invocations per keySP 800-38D section 8.3 [2]
StandardNIST SP 800-38D, FIPS 197[2][5]

Security Best Practices

  • Never reuse an IV with the same key. If an IV repeats, an attacker is likely to be able to determine the hash subkey and then forge ciphertexts [2].
  • Use 12-byte (96-bit) IVs. Any other length is first processed with GHASH to form the initial counter block [2], and the 2^32 invocation limit then applies even to deterministic IVs [2].
  • Verify the tag before using plaintext. AuthenticatedDecryptionFilter throws on failure, but it has already passed decrypted bytes to its attachment [11]; with the one-shot API, check the return value.
  • Store keys in SecByteBlock. Its allocator wipes the memory before freeing it [12].

IV Selection

IVs must be unique, not necessarily random. Two constructions are allowed:

  1. Deterministic IV. A fixed field that identifies the device or context, followed by an invocation counter; NIST suggests a 32-bit fixed field and a 64-bit counter for 96-bit IVs.
  2. RBG-based IV. At least 96 random bits from an approved generator; limit to 2^32 messages per key [2].

Test Vector

This AES-128-GCM vector includes AAD. It is one of the GCM vectors in the library’s test suite [13].

// AES-128-GCM Test Vector
byte key[] = {
    0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c,
    0x6d, 0x6a, 0x8f, 0x94, 0x67, 0x30, 0x83, 0x08
};

byte iv[] = {
    0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad,
    0xde, 0xca, 0xf8, 0x88
};

// Additional authenticated data
byte aad[] = {
    0xfe, 0xed, 0xfa, 0xce, 0xde, 0xad, 0xbe, 0xef,
    0xfe, 0xed, 0xfa, 0xce, 0xde, 0xad, 0xbe, 0xef,
    0xab, 0xad, 0xda, 0xd2
};

byte plaintext[] = {
    0xd9, 0x31, 0x32, 0x25, 0xf8, 0x84, 0x06, 0xe5,
    0xa5, 0x59, 0x09, 0xc5, 0xaf, 0xf5, 0x26, 0x9a,
    0x86, 0xa7, 0xa9, 0x53, 0x15, 0x34, 0xf7, 0xda,
    0x2e, 0x4c, 0x30, 0x3d, 0x8a, 0x31, 0x8a, 0x72,
    0x1c, 0x3c, 0x0c, 0x95, 0x95, 0x68, 0x09, 0x53,
    0x2f, 0xcf, 0x0e, 0x24, 0x49, 0xa6, 0xb5, 0x25,
    0xb1, 0x6a, 0xed, 0xf5, 0xaa, 0x0d, 0xe6, 0x57,
    0xba, 0x63, 0x7b, 0x39
};

// Expected ciphertext
byte expected_ciphertext[] = {
    0x42, 0x83, 0x1e, 0xc2, 0x21, 0x77, 0x74, 0x24,
    0x4b, 0x72, 0x21, 0xb7, 0x84, 0xd0, 0xd4, 0x9c,
    0xe3, 0xaa, 0x21, 0x2f, 0x2c, 0x02, 0xa4, 0xe0,
    0x35, 0xc1, 0x7e, 0x23, 0x29, 0xac, 0xa1, 0x2e,
    0x21, 0xd5, 0x14, 0xb2, 0x54, 0x66, 0x93, 0x1c,
    0x7d, 0x8f, 0x6a, 0x5a, 0xac, 0x84, 0xaa, 0x05,
    0x1b, 0xa3, 0x0b, 0x39, 0x6a, 0x0a, 0xac, 0x97,
    0x3d, 0x58, 0xe0, 0x91
};

// Expected authentication tag (depends on the AAD above)
byte expected_tag[] = {
    0x5b, 0xc9, 0x4f, 0xbc, 0x32, 0x21, 0xa5, 0xdb,
    0x94, 0xfa, 0xe9, 0x5a, 0xe7, 0x12, 0x1a, 0x47
};

Common Patterns

Generate Key from Password

#include <cryptopp/pwdbased.h>
#include <cryptopp/sha.h>

SecByteBlock deriveKey(const std::string& password,
                       const byte* salt, size_t saltLen) {
    SecByteBlock key(32);  // 256-bit key

    PKCS5_PBKDF2_HMAC<SHA256> pbkdf;
    pbkdf.DeriveKey(
        key, key.size(),
        0,  // unused
        (const byte*)password.data(), password.size(),
        salt, saltLen,
        100000  // iterations: see the password hashing guide for current values
    );

    return key;
}

Stream Processing

void encryptLargeFile(const std::string& infile,
                      const std::string& outfile,
                      const SecByteBlock& key) {
    using namespace CryptoPP;

    AutoSeededRandomPool rng;
    byte iv[12];
    rng.GenerateBlock(iv, sizeof(iv));

    GCM<AES>::Encryption enc;
    enc.SetKeyWithIV(key, key.size(), iv, sizeof(iv));

    // Write IV first
    FileSink out(outfile.c_str());
    out.Put(iv, sizeof(iv));

    // Stream encryption
    FileSource(infile.c_str(), true,
        new AuthenticatedEncryptionFilter(enc,
            new Redirector(out)
        )
    );
}

Thread Safety

Not thread-safe. Create separate GCM<AES>::Encryption and GCM<AES>::Decryption objects for each thread.

// WRONG - sharing between threads
GCM<AES>::Encryption shared_enc;

// CORRECT - one per thread
void threadFunc() {
    GCM<AES>::Encryption enc;  // Thread-local
    // ... use enc ...
}

Exceptions

  • InvalidKeyLength - Key size is not 16, 24, or 32 bytes [9]
  • InvalidArgument - IV length out of range, zero-length or over-long tag, or over-long input [8][9]
  • HashVerificationFilter::HashVerificationFailed - Authentication tag verification failed in AuthenticatedDecryptionFilter [11]

Algorithm Details

  • Algorithm: AES (Rijndael with 128-bit blocks) [5]
  • Mode: GCM (Galois/Counter Mode) [2]
  • Key sizes: 128, 192, or 256 bits [5]
  • Block size: 128 bits (fixed) [5]
  • IV size: 96 bits recommended; SP 800-38D allows 1 to 2^64-1 bits, and the library accepts 1 to UINT_MAX bytes [2][7]
  • Tag size: SP 800-38D allows 128, 120, 112, 104 or 96 bits, and 64 or 32 bits only for certain applications [2]. The library accepts any tag from 1 to 16 bytes, so choosing a permitted length is up to the caller [7][8]
  • Maximum plaintext: 2^39-256 bits per invocation [2][7]
  • Standard: FIPS 197 (AES), NIST SP 800-38D (GCM) [2][5]

See Also

References

  1. cryptopp-modern History.txt at 2026.11.0, release 3.1 (Rijndael), and lines 630-631, release 5.6.0 (GCM).
  2. NIST SP 800-38D: Galois/Counter Mode (GCM) and GMAC, sections 3, 5.2.1.1, 5.2.1.2, 7.1, 8, 8.2, 8.3 and appendices A to C.
  3. RFC 8446: The Transport Layer Security (TLS) Protocol Version 1.3, appendix B.4.
  4. RFC 4106: The Use of Galois/Counter Mode (GCM) in IPsec Encapsulating Security Payload (ESP), abstract.
  5. FIPS 197: Advanced Encryption Standard (AES), section 5, table 3.
  6. rijndael.h at 2026.11.0, Rijndael_Info: 16-byte block, keys of 16 to 32 bytes in steps of 8.
  7. gcm.h at 2026.11.0, algorithm provider, IV sizes, tag size and maximum lengths.
  8. authenc.cpp at 2026.11.0, tag and length checks; cryptlib.cpp, SpecifyDataLengths(); cryptlib.h, NeedsPrespecifiedDataLengths().
  9. cryptlib.cpp at 2026.11.0, key and IV length checks, and lines 415-419, tag longer than the digest.
  10. cryptlib.h at 2026.11.0, DecryptAndVerify().
  11. filters.cpp at 2026.11.0, AuthenticatedDecryptionFilter forwards decrypted data before the final tag check.
  12. secblock.h at 2026.11.0, AllocatorWithCleanup::deallocate wipes before freeing.
  13. TestVectors/gcm.txt at 2026.11.0, AES/GCM vector with header (AAD).