Skip to content

AES-CTR-HMAC

Header: #include <cryptopp/aes_ctr_hmac.h> Namespace: CryptoPP Since: cryptopp-modern 2026.1.0 [1] Thread Safety: Not thread-safe per instance; use separate instances per thread

AES-CTR-HMAC is an Encrypt-then-MAC authenticated encryption scheme combining AES in Counter mode with HMAC for authentication. Unlike manual CBC+HMAC constructions, this implementation derives separate encryption and MAC keys from a single master key using HKDF. The construction and its output format are defined by this library’s header, not by an external standard [2].

Quick Example

#include <cryptopp/aes_ctr_hmac.h>
#include <cryptopp/osrng.h>
#include <iostream>

int main() {
    using namespace CryptoPP;

    AutoSeededRandomPool rng;

    // Generate a 32-byte master key (AES-256)
    SecByteBlock masterKey(32);
    rng.GenerateBlock(masterKey, masterKey.size());

    // Generate a unique 12-byte IV
    byte iv[12];
    rng.GenerateBlock(iv, sizeof(iv));

    std::string plaintext = "Secret message";
    std::string ciphertext(plaintext.size(), '\0');
    byte tag[16];

    // Encrypt
    AES_CTR_HMAC_SHA256::Encryption enc;
    enc.SetKeyWithIV(masterKey, masterKey.size(), iv, sizeof(iv));
    enc.EncryptAndAuthenticate(
        reinterpret_cast<byte*>(&ciphertext[0]), tag, sizeof(tag),
        iv, sizeof(iv),
        nullptr, 0,  // No AAD
        (const byte*)plaintext.data(), plaintext.size()
    );

    std::cout << "Encrypted " << plaintext.size() << " bytes" << std::endl;

    // Decrypt and verify
    std::string recovered(ciphertext.size(), '\0');
    AES_CTR_HMAC_SHA256::Decryption dec;
    dec.SetKeyWithIV(masterKey, masterKey.size(), iv, sizeof(iv));

    bool valid = dec.DecryptAndVerify(
        reinterpret_cast<byte*>(&recovered[0]), tag, sizeof(tag),
        iv, sizeof(iv),
        nullptr, 0,  // No AAD
        (const byte*)ciphertext.data(), ciphertext.size()
    );

    if (valid) {
        std::cout << "Decrypted: " << recovered << std::endl;
    } else {
        std::cerr << "Authentication failed!" << std::endl;
    }

    return 0;
}

Usage Guidelines

Do:

  • Use a 12-byte IV that is unique per message under the same key
  • Use 32-byte master keys for AES-256, or 16/24 bytes for AES-128/192 [2]
  • Always check the return value of DecryptAndVerify()
  • Use AAD (additional authenticated data) for data that needs authentication but not encryption

Avoid:

  • Reusing IVs with the same key; under CTR mode this exposes the plaintexts [2][3]
  • Ignoring authentication failures during decryption
  • Calling Restart() between messages; it throws BadState. Use Resynchronize() with a fresh IV instead [2]

A random 12-byte IV is the same size as a GCM IV. We recommend keeping to the 2^32 messages per key that SP 800-38D sets for random 96-bit GCM IVs [4], or using a counter. For password-based encryption, we recommend deriving the master key with a password hashing function such as Argon2 rather than using the password directly.

Why AES-CTR-HMAC?

AES-CTR-HMAC sits between AES-GCM and manual CBC+HMAC in the design tradeoffs:

FeatureAES-CTR-HMACAES-GCMAES-CBC+HMAC
Key managementSingle master key [2]Single keyTwo separate keys
Key derivationAutomatic (HKDF) [2]NoneManual
Encryption parallelisableYes (CTR) [3]Yes [4]No (CBC) [3]
Padding requiredNo [3]No [4]Yes [3]
PrimitivesAES + HMAC + HKDF [2]AES + GHASH [4]AES + HMAC

Choose AES-CTR-HMAC when:

  • You want simpler key management (one master key instead of two)
  • You need automatic key derivation with the algorithm names bound into the derivation and the tag
  • You want an HMAC-based tag that may be longer than 16 bytes [2]

Choose AES-GCM when:

  • You need a standard construction that other implementations can read, such as for TLS 1.3 [4][5]

Key Derivation

AES-CTR-HMAC derives separate encryption and MAC keys from your master key using HKDF, with no salt and the domain string as the info parameter [2]:

Master Key (16/24/32 bytes)
         │
         ▼
    ┌─────────┐
    │  HKDF   │  info = "{BlockCipher}-CTR-HMAC-" + HashName
    └────┬────┘     (e.g. "AES-CTR-HMAC-SHA-256")
         │
    ┌────┴────┐
    ▼         ▼
Encryption   MAC Key
   Key       (hash digest size:
(same size    32 bytes for SHA-256,
as master)    64 bytes for SHA-512)

The master key length determines the AES variant [2]:

  • 16 bytes: AES-128
  • 24 bytes: AES-192
  • 32 bytes: AES-256

IV/Nonce Requirements

  • Fixed 12-byte IV - Must be unique per message under the same key
  • Counter format: IV || 0x00000001 (16 bytes total, big-endian)
  • Counter starts at 1, reserving block 0 [2]
// Generate a random IV for each message
AutoSeededRandomPool rng;
byte iv[12];
rng.GenerateBlock(iv, sizeof(iv));

enc.SetKeyWithIV(masterKey, masterKey.size(), iv, sizeof(iv));
Never reuse an IV with the same key. CTR mode XORs the keystream with plaintext; a repeated counter block lets anyone who knows one plaintext block recover the other [3].

MAC Construction

The HMAC is computed over a structured input to bind ciphertext to its context [2]:

HMAC Input:
┌─────────────────────────────────────┐
│ Domain: "{BlockCipher}-CTR-HMAC-" +     │  (ASCII string)
│         HashName                         │
│         e.g. "AES-CTR-HMAC-SHA-256"     │
├─────────────────────────────────────┤
│ Separator: 0x00                     │  (1 byte)
├─────────────────────────────────────┤
│ IV                                  │  (12 bytes)
├─────────────────────────────────────┤
│ AAD                                 │  (variable)
├─────────────────────────────────────┤
│ Ciphertext                          │  (variable)
├─────────────────────────────────────┤
│ len(AAD) || len(Ciphertext)         │  (16 bytes, big-endian)
└─────────────────────────────────────┘

This construction:

  • Binds the tag to the block cipher and hash names through the domain string
  • Authenticates the IV
  • Encodes both lengths, so the split between AAD and ciphertext is authenticated

Complete Example: With Additional Authenticated Data

#include <cryptopp/aes_ctr_hmac.h>
#include <cryptopp/osrng.h>
#include <iostream>

int main() {
    using namespace CryptoPP;

    AutoSeededRandomPool rng;

    // Generate master key and IV
    SecByteBlock masterKey(32);  // AES-256
    byte iv[12];
    rng.GenerateBlock(masterKey, masterKey.size());
    rng.GenerateBlock(iv, sizeof(iv));

    // Message and AAD
    std::string plaintext = "Confidential payload";
    std::string aad = "packet-header:12345";  // Authenticated but not encrypted

    // Encrypt with AAD
    std::string ciphertext(plaintext.size(), '\0');
    byte tag[16];

    AES_CTR_HMAC_SHA256::Encryption enc;
    enc.SetKeyWithIV(masterKey, masterKey.size(), iv, sizeof(iv));
    enc.EncryptAndAuthenticate(
        reinterpret_cast<byte*>(&ciphertext[0]), tag, sizeof(tag),
        iv, sizeof(iv),
        (const byte*)aad.data(), aad.size(),
        (const byte*)plaintext.data(), plaintext.size()
    );

    // Decrypt with AAD verification
    std::string recovered(ciphertext.size(), '\0');

    AES_CTR_HMAC_SHA256::Decryption dec;
    dec.SetKeyWithIV(masterKey, masterKey.size(), iv, sizeof(iv));

    bool valid = dec.DecryptAndVerify(
        reinterpret_cast<byte*>(&recovered[0]), tag, sizeof(tag),
        iv, sizeof(iv),
        (const byte*)aad.data(), aad.size(),  // Must match!
        (const byte*)ciphertext.data(), ciphertext.size()
    );

    if (valid) {
        std::cout << "AAD: " << aad << std::endl;
        std::cout << "Decrypted: " << recovered << std::endl;
    } else {
        std::cerr << "Authentication failed - AAD or ciphertext tampered!" << std::endl;
    }

    return 0;
}

Complete Example: Using Pipeline Filters

The filters use the object’s DigestSize() unless you pass a tag size, and for AES-CTR-HMAC that is the full HMAC output (32 bytes for SHA-256) [2][6]. The example passes 16 to both filters so the tag matches the one-shot calls above.

#include <cryptopp/aes_ctr_hmac.h>
#include <cryptopp/filters.h>
#include <cryptopp/osrng.h>
#include <iostream>

int main() {
    using namespace CryptoPP;

    AutoSeededRandomPool rng;

    SecByteBlock masterKey(32);
    byte iv[12];
    rng.GenerateBlock(masterKey, masterKey.size());
    rng.GenerateBlock(iv, sizeof(iv));

    const int TAG_SIZE = 16;

    std::string plaintext = "Hello, authenticated encryption!";
    std::string ciphertext;

    // Encrypt using pipeline
    AES_CTR_HMAC_SHA256::Encryption enc;
    enc.SetKeyWithIV(masterKey, masterKey.size(), iv, sizeof(iv));

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

    std::cout << "Ciphertext + tag: " << ciphertext.size() << " bytes" << std::endl;

    // Decrypt using pipeline
    std::string recovered;
    AES_CTR_HMAC_SHA256::Decryption dec;
    dec.SetKeyWithIV(masterKey, masterKey.size(), iv, sizeof(iv));

    try {
        StringSource(ciphertext, true,
            new AuthenticatedDecryptionFilter(dec,
                new StringSink(recovered),
                AuthenticatedDecryptionFilter::DEFAULT_FLAGS, TAG_SIZE
            )
        );
        std::cout << "Decrypted: " << recovered << std::endl;
    } catch (const HashVerificationFilter::HashVerificationFailed& e) {
        std::cerr << "Authentication failed: " << e.what() << std::endl;
    }

    return 0;
}

Using SHA-512

#include <cryptopp/aes_ctr_hmac.h>
#include <cryptopp/osrng.h>

int main() {
    using namespace CryptoPP;

    AutoSeededRandomPool rng;
    SecByteBlock masterKey(32);
    byte iv[12];
    rng.GenerateBlock(masterKey, masterKey.size());
    rng.GenerateBlock(iv, sizeof(iv));

    std::string plaintext = "High security message";
    std::string ciphertext(plaintext.size(), '\0');
    byte tag[16];  // Still 16-byte tag (truncated from 64-byte HMAC-SHA512)

    // Use SHA-512 variant
    AES_CTR_HMAC_SHA512::Encryption enc;
    enc.SetKeyWithIV(masterKey, masterKey.size(), iv, sizeof(iv));
    enc.EncryptAndAuthenticate(
        reinterpret_cast<byte*>(&ciphertext[0]), tag, sizeof(tag),
        iv, sizeof(iv),
        nullptr, 0,
        (const byte*)plaintext.data(), plaintext.size()
    );

    return 0;
}

Class Reference

Type Aliases

// SHA-256 variant
typedef AES_CTR_HMAC<AES, SHA256> AES_CTR_HMAC_SHA256;

// SHA-512 variant
typedef AES_CTR_HMAC<AES, SHA512> AES_CTR_HMAC_SHA512;

Both typedefs are declared in the header [2].

AES_CTR_HMAC<>::Encryption

SetKeyWithIV()

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

Set the master key and IV. The master key is expanded via HKDF into separate encryption and MAC keys [2].

Parameters:

  • key - Master key (16, 24, or 32 bytes); must not be null
  • keyLength - Length of master key
  • iv - Initialization vector (must be 12 bytes); must not be null
  • ivLength - Length of IV (must be 12)

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); must not be null if messageLength > 0
  • mac - Output authentication tag; must not be null
  • macSize - Size of MAC output. Must be between 12 and the hash digest size (32 for SHA-256, 64 for SHA-512); values outside this range throw InvalidArgument [2]
  • iv - Initialization vector (12 bytes); must not be null
  • ivLength - IV length
  • aad - Additional authenticated data (can be NULL if aadLength is 0)
  • aadLength - AAD length
  • message - Plaintext to encrypt (can be NULL if messageLength is 0)
  • messageLength - Plaintext length; must not exceed MaxMessageLength()

AES_CTR_HMAC<>::Decryption

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.

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

Important: Always check the return value. If false, the message has been tampered with and the output should be discarded.

Size Accessors

The following methods return size information [2]:

Key sizes (determined by master key length):

  • MinKeyLength() returns 16 (AES-128)
  • MaxKeyLength() returns 32 (AES-256)
  • DefaultKeyLength() returns 16

IV size (fixed):

  • IVSize() returns 12

Tag size:

  • TagSize() returns 16, the size the one-shot examples on this page use
  • DigestSize() returns the hash digest size, and the filters use it when no tag size is given [6]
  • Minimum tag size is 12 bytes; maximum is the hash digest size (32 for SHA-256, 64 for SHA-512)

Message length limit:

  • MaxMessageLength() returns (2^32 - 1) x 16 bytes (about 68.7 GB)
  • This limit prevents the 32-bit CTR counter from overflowing into the IV portion

Security

Quick Summary

AspectValue
Key derivationHKDF with the domain string as info
EncryptionAES-CTR (128/192/256-bit)
AuthenticationHMAC-SHA256 or HMAC-SHA512
IV size96 bits (12 bytes)
Tag size128 bits for TagSize(); min 96 bits, max = hash digest size
ConstructionEncrypt-then-MAC
Max messageAbout 68.7 GB (counter overflow protection)

Source: [2].

Security Properties

  • Confidentiality: Provided by AES-CTR with the derived encryption key
  • Authenticity: Provided by HMAC over the domain string, IV, AAD, ciphertext, and lengths
  • Key separation: HKDF derives separate encryption and MAC keys from the master key
  • Domain separation: Block cipher and hash algorithm names included in HKDF info and MAC input
  • Length encoding: Both lengths are included in the MAC input [2]
  • Streaming misuse protection: Restart() throws BadState to prevent accidental IV reuse; use Resynchronize() with a fresh IV for new messages [2]
  • Counter overflow protection: MaxMessageLength() enforces a limit to prevent the CTR counter from wrapping [2]

Comparison with AES-GCM

PropertyAES-CTR-HMACAES-GCM
IV reuse impactCTR keystream reuse exposes the plaintexts [3]Hash subkey likely recoverable, then forgeries [4]
Key separationBuilt-in (HKDF splits enc + MAC keys) [2]Requires external KDF if deriving from master key
SpecificationThis library’s header [2]NIST SP 800-38D [4]

Thread Safety

Not thread-safe. Create separate Encryption and Decryption objects for each thread.

// WRONG - sharing between threads
AES_CTR_HMAC_SHA256::Encryption shared_enc;

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

Exceptions

  • InvalidKeyLength - Master key size is not 16, 24, or 32 bytes. The check happens when the AES key is set, which is when an IV is supplied [2][7]
  • InvalidArgument - IV length is not 12 bytes, macSize is outside the range [12, digest size], message exceeds MaxMessageLength(), or null pointer passed for required buffer [2]
  • BadState - Restart() was called (use Resynchronize() with a fresh IV instead) [2]
  • HashVerificationFilter::HashVerificationFailed - Authentication tag verification failed (when using filters) [8]

See Also

References

  1. cryptopp-modern History.txt at 2026.11.0, release 2026.1.0: “added AES-CTR-HMAC authenticated encryption”.
  2. aes_ctr_hmac.h at 2026.11.0, design notes, size accessors, tag checks, Restart() and typedefs; lines 245-414 for key derivation, counter block, MAC input and the one-shot functions.
  3. NIST SP 800-38A: Recommendation for Block Cipher Modes of Operation, sections 6.2 and 6.5, appendices A and B.
  4. NIST SP 800-38D: Galois/Counter Mode (GCM) and GMAC, sections 3, 5.2.1.1 and 8.3, appendix A.
  5. RFC 8446: The Transport Layer Security (TLS) Protocol Version 1.3, appendix B.4.
  6. filters.cpp at 2026.11.0, HashFilter uses DigestSize() when no tag size is given, and lines 898-902 for HashVerificationFilter.
  7. modes.h at 2026.11.0, mode key lengths come from the block cipher; cryptlib.cpp, SetKey() throws InvalidKeyLength.
  8. filters.cpp at 2026.11.0, AuthenticatedDecryptionFilter.