Skip to content

AES-CBC with HMAC

Header: #include <cryptopp/aes.h>, #include <cryptopp/modes.h>,
and #include <cryptopp/hmac.h> Namespace: CryptoPP
Since: Crypto++ 3.1 (AES, as Rijndael), 5.0 (current CBC mode interface), 2.1 (HMAC) [1]
Thread Safety: Not thread-safe per instance; use separate instances per thread

AES-CBC (Cipher Block Chaining) with HMAC provides authenticated encryption using the Encrypt-then-MAC construction. While modern applications should prefer AES-GCM or ChaCha20-Poly1305, CBC+HMAC remains useful where an existing format or system requires CBC.

TLS 1.2 CBC cipher suites compute the MAC before encrypting (MAC-then-encrypt) [2]; RFC 7366 defines an extension that switches TLS to encrypt-then-MAC [3]. The construction on this page is encrypt-then-MAC, so it is not the default TLS 1.2 record format.

Quick Example

#include <cryptopp/aes.h>
#include <cryptopp/modes.h>
#include <cryptopp/hmac.h>
#include <cryptopp/sha.h>
#include <cryptopp/osrng.h>
#include <cryptopp/filters.h>
#include <iostream>

int main() {
    using namespace CryptoPP;

    AutoSeededRandomPool rng;

    // Generate keys
    SecByteBlock aesKey(AES::DEFAULT_KEYLENGTH);   // 128-bit
    SecByteBlock hmacKey(SHA256::DIGESTSIZE);       // 256-bit
    byte iv[AES::BLOCKSIZE];                        // 128-bit IV

    rng.GenerateBlock(aesKey, aesKey.size());
    rng.GenerateBlock(hmacKey, hmacKey.size());
    rng.GenerateBlock(iv, sizeof(iv));

    std::string plaintext = "Secret message";

    // Encrypt with AES-CBC
    std::string ciphertext;
    CBC_Mode<AES>::Encryption enc;
    enc.SetKeyWithIV(aesKey, aesKey.size(), iv);

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

    // Compute HMAC over IV + ciphertext
    std::string mac;
    HMAC<SHA256> hmac(hmacKey, hmacKey.size());

    StringSource(std::string((char*)iv, sizeof(iv)) + ciphertext, true,
        new HashFilter(hmac,
            new StringSink(mac)
        )
    );

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

    // In a real protocol, 'receivedMac' would come from the peer
    std::string receivedMac = mac;

    // Verify HMAC (constant-time) before decrypting
    std::string computedMac;
    HMAC<SHA256> hmacVerify(hmacKey, hmacKey.size());

    StringSource(std::string((char*)iv, sizeof(iv)) + ciphertext, true,
        new HashFilter(hmacVerify,
            new StringSink(computedMac)
        )
    );

    // Check the length first, then compare in constant time
    if (receivedMac.size() != SHA256::DIGESTSIZE ||
        !VerifyBufsEqual(
            reinterpret_cast<const byte*>(receivedMac.data()),
            reinterpret_cast<const byte*>(computedMac.data()),
            SHA256::DIGESTSIZE))
    {
        std::cerr << "Authentication failed!" << std::endl;
        return 1;
    }

    // Decrypt
    std::string recovered;
    CBC_Mode<AES>::Decryption dec;
    dec.SetKeyWithIV(aesKey, aesKey.size(), iv);

    StringSource(ciphertext, true,
        new StreamTransformationFilter(dec,
            new StringSink(recovered)
        )
    );

    std::cout << "Decrypted: " << recovered << std::endl;

    return 0;
}

VerifyBufsEqual() compares two buffers of the same size in near constant time and leaves length checking to the caller [4], which is why the received MAC’s length is checked first.

Usage Guidelines

Modern Applications: Use AES-GCM or ChaCha20-Poly1305 instead.

Use AES-CBC+HMAC only for:

  • Legacy system compatibility
  • Formats that require CBC mode
  • When AEAD ciphers are not available

Critical Requirements:

  • ALWAYS use Encrypt-then-MAC (not MAC-then-Encrypt) [3]
  • ALWAYS verify HMAC before decrypting
  • NEVER reuse IVs with the same key
  • Use unpredictable IVs, such as random IVs from a CSPRNG [5]
  • Include IV in HMAC computation
  • Use separate keys for AES and HMAC

Padding Warning: RFC 5246 records a timing attack on CBC padding [2]. Only decrypt after HMAC verification succeeds.

Encrypt-then-MAC Construction

The construction is:

  1. Generate an unpredictable IV [5]
  2. Encrypt plaintext with AES-CBC (produces ciphertext with padding)
  3. Compute HMAC over (IV || ciphertext)
  4. Send: IV || ciphertext || MAC

To decrypt:

  1. Verify HMAC over (IV || ciphertext)
  2. ONLY if HMAC valid, decrypt ciphertext
  3. NEVER decrypt before HMAC verification

Complete Example: Secure Authenticated Encryption

#include <cryptopp/aes.h>
#include <cryptopp/modes.h>
#include <cryptopp/hmac.h>
#include <cryptopp/sha.h>
#include <cryptopp/osrng.h>
#include <cryptopp/filters.h>
#include <stdexcept>
#include <iostream>

using namespace CryptoPP;

class AES_CBC_HMAC {
public:
    AES_CBC_HMAC(const SecByteBlock& aesKey,
                 const SecByteBlock& hmacKey)
        : m_aesKey(aesKey), m_hmacKey(hmacKey) {
        // This example uses AES-128; adapt check for 192/256-bit keys if needed
        if (aesKey.size() != AES::DEFAULT_KEYLENGTH) {
            throw std::invalid_argument("AES key must be 16 bytes");
        }
        // HMAC key of 32 bytes is a good default; other sizes work too
        if (hmacKey.size() != SHA256::DIGESTSIZE) {
            throw std::invalid_argument("HMAC key must be 32 bytes");
        }
    }

    struct EncryptedMessage {
        byte iv[AES::BLOCKSIZE];
        std::string ciphertext;
        byte mac[SHA256::DIGESTSIZE];
    };

    EncryptedMessage encrypt(const std::string& plaintext) {
        EncryptedMessage msg;
        AutoSeededRandomPool rng;

        // Generate random IV
        rng.GenerateBlock(msg.iv, sizeof(msg.iv));

        // Encrypt with AES-CBC
        CBC_Mode<AES>::Encryption enc;
        enc.SetKeyWithIV(m_aesKey, m_aesKey.size(), msg.iv);

        StringSource(plaintext, true,
            new StreamTransformationFilter(enc,
                new StringSink(msg.ciphertext)
            )
        );

        // Compute HMAC over IV + ciphertext
        HMAC<SHA256> hmac(m_hmacKey, m_hmacKey.size());
        std::string macData(reinterpret_cast<char*>(msg.iv), sizeof(msg.iv));
        macData += msg.ciphertext;

        StringSource(macData, true,
            new HashFilter(hmac,
                new ArraySink(msg.mac, sizeof(msg.mac))
            )
        );

        return msg;
    }

    std::string decrypt(const EncryptedMessage& msg) {
        // Verify HMAC BEFORE decrypting
        HMAC<SHA256> hmac(m_hmacKey, m_hmacKey.size());
        std::string macData(reinterpret_cast<const char*>(msg.iv), sizeof(msg.iv));
        macData += msg.ciphertext;

        byte computedMac[SHA256::DIGESTSIZE];
        StringSource(macData, true,
            new HashFilter(hmac,
                new ArraySink(computedMac, sizeof(computedMac))
            )
        );

        // Constant-time comparison
        if (!VerifyBufsEqual(msg.mac, computedMac, sizeof(msg.mac))) {
            throw std::runtime_error("Authentication failed - HMAC mismatch");
        }

        // HMAC verified - safe to decrypt
        std::string recovered;
        CBC_Mode<AES>::Decryption dec;
        dec.SetKeyWithIV(m_aesKey, m_aesKey.size(), msg.iv);

        try {
            StringSource(msg.ciphertext, true,
                new StreamTransformationFilter(dec,
                    new StringSink(recovered)
                )
            );
        } catch (const Exception& e) {
            throw std::runtime_error("Decryption failed");
        }

        return recovered;
    }

private:
    SecByteBlock m_aesKey;
    SecByteBlock m_hmacKey;
};

int main() {
    AutoSeededRandomPool rng;

    // Generate separate keys for AES and HMAC
    SecByteBlock aesKey(AES::DEFAULT_KEYLENGTH);   // 128-bit
    SecByteBlock hmacKey(SHA256::DIGESTSIZE);       // 256-bit

    rng.GenerateBlock(aesKey, aesKey.size());
    rng.GenerateBlock(hmacKey, hmacKey.size());

    AES_CBC_HMAC cipher(aesKey, hmacKey);

    // Encrypt message
    std::string plaintext = "Confidential document";
    auto encrypted = cipher.encrypt(plaintext);

    std::cout << "Encrypted: " << encrypted.ciphertext.size()
              << " bytes + " << sizeof(encrypted.iv) << " IV + "
              << sizeof(encrypted.mac) << " MAC" << std::endl;

    // Decrypt message
    try {
        std::string decrypted = cipher.decrypt(encrypted);
        std::cout << "Decrypted: " << decrypted << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }

    // Try tampering with ciphertext
    encrypted.ciphertext[0] ^= 0x01;  // Flip one bit
    try {
        std::string decrypted = cipher.decrypt(encrypted);
        std::cout << "ERROR: Should have failed!" << std::endl;
    } catch (const std::exception& e) {
        std::cout << "Correctly rejected tampered message: "
                  << e.what() << std::endl;
    }

    return 0;
}

Complete Example: File Encryption

The decryption side checks the HMAC over the whole file before it decrypts anything, so no unauthenticated plaintext reaches the output file.

#include <cryptopp/aes.h>
#include <cryptopp/modes.h>
#include <cryptopp/hmac.h>
#include <cryptopp/sha.h>
#include <cryptopp/osrng.h>
#include <cryptopp/files.h>
#include <cryptopp/filters.h>
#include <iostream>

using namespace CryptoPP;

void encryptFile(const std::string& inputFile,
                 const std::string& outputFile,
                 const SecByteBlock& aesKey,
                 const SecByteBlock& hmacKey) {
    AutoSeededRandomPool rng;

    // Generate random IV
    byte iv[AES::BLOCKSIZE];
    rng.GenerateBlock(iv, sizeof(iv));

    // Open output file
    FileSink outFile(outputFile.c_str());

    // Write IV first
    outFile.Put(iv, sizeof(iv));

    // Encrypt file to temporary string (for HMAC)
    std::string ciphertext;
    CBC_Mode<AES>::Encryption enc;
    enc.SetKeyWithIV(aesKey, aesKey.size(), iv);

    FileSource(inputFile.c_str(), true,
        new StreamTransformationFilter(enc,
            new StringSink(ciphertext)
        )
    );

    // Write ciphertext
    outFile.Put((const byte*)ciphertext.data(), ciphertext.size());

    // Compute HMAC over IV + ciphertext
    HMAC<SHA256> hmac(hmacKey, hmacKey.size());
    std::string macData(reinterpret_cast<char*>(iv), sizeof(iv));
    macData += ciphertext;

    byte mac[SHA256::DIGESTSIZE];
    StringSource(macData, true,
        new HashFilter(hmac,
            new ArraySink(mac, sizeof(mac))
        )
    );

    // Write MAC
    outFile.Put(mac, sizeof(mac));

    std::cout << "File encrypted: " << outputFile << std::endl;
    std::cout << "IV: " << sizeof(iv) << " bytes" << std::endl;
    std::cout << "Ciphertext: " << ciphertext.size() << " bytes" << std::endl;
    std::cout << "MAC: " << sizeof(mac) << " bytes" << std::endl;
}

void decryptFile(const std::string& inputFile,
                 const std::string& outputFile,
                 const SecByteBlock& aesKey,
                 const SecByteBlock& hmacKey) {
    // Read entire encrypted file
    std::string fileData;
    FileSource(inputFile.c_str(), true,
        new StringSink(fileData)
    );

    // Extract components
    const size_t ivSize = AES::BLOCKSIZE;
    const size_t macSize = SHA256::DIGESTSIZE;

    if (fileData.size() < ivSize + macSize) {
        throw std::runtime_error("Invalid encrypted file format");
    }

    byte iv[AES::BLOCKSIZE];
    memcpy(iv, fileData.data(), ivSize);

    size_t ciphertextSize = fileData.size() - ivSize - macSize;
    std::string ciphertext = fileData.substr(ivSize, ciphertextSize);

    byte mac[SHA256::DIGESTSIZE];
    memcpy(mac, fileData.data() + ivSize + ciphertextSize, macSize);

    // Verify HMAC BEFORE decrypting
    HMAC<SHA256> hmac(hmacKey, hmacKey.size());
    std::string macData(reinterpret_cast<char*>(iv), ivSize);
    macData += ciphertext;

    byte computedMac[SHA256::DIGESTSIZE];
    StringSource(macData, true,
        new HashFilter(hmac,
            new ArraySink(computedMac, sizeof(computedMac))
        )
    );

    // Constant-time comparison
    if (!VerifyBufsEqual(mac, computedMac, macSize)) {
        throw std::runtime_error("Authentication failed - file may be corrupted or tampered");
    }

    std::cout << "HMAC verified successfully" << std::endl;

    // HMAC verified - safe to decrypt
    CBC_Mode<AES>::Decryption dec;
    dec.SetKeyWithIV(aesKey, aesKey.size(), iv);

    StringSource(ciphertext, true,
        new StreamTransformationFilter(dec,
            new FileSink(outputFile.c_str())
        )
    );

    std::cout << "File decrypted: " << outputFile << std::endl;
}

int main() {
    AutoSeededRandomPool rng;

    // Generate keys
    SecByteBlock aesKey(AES::DEFAULT_KEYLENGTH);
    SecByteBlock hmacKey(SHA256::DIGESTSIZE);

    rng.GenerateBlock(aesKey, aesKey.size());
    rng.GenerateBlock(hmacKey, hmacKey.size());

    // Encrypt file
    encryptFile("document.pdf", "document.pdf.enc", aesKey, hmacKey);

    // Decrypt file
    try {
        decryptFile("document.pdf.enc", "document_recovered.pdf", aesKey, hmacKey);
    } catch (const std::exception& e) {
        std::cerr << "Decryption failed: " << e.what() << std::endl;
    }

    return 0;
}

Key Sizes

AES Key Sizes

// 128-bit
SecByteBlock key128(AES::DEFAULT_KEYLENGTH);  // 16 bytes

// 192-bit
SecByteBlock key192(24);

// 256-bit
SecByteBlock key256(AES::MAX_KEYLENGTH);  // 32 bytes

AES is defined for these three key sizes [6]. See Security Levels for what they mean.

HMAC Key Sizes

// SHA-256
SecByteBlock hmacKey(SHA256::DIGESTSIZE);  // 32 bytes

// SHA-512
SecByteBlock hmacKey(SHA512::DIGESTSIZE);  // 64 bytes

Performance

CBC encryption cannot be parallelized [5], and HMAC is a separate pass over the ciphertext.

Security

Quick Summary

AspectRecommendationWhy it matters
ConstructionEncrypt-then-MAC onlyMAC-then-encrypt has a long record of vulnerabilities [3]
IVUnpredictable 16-byte IV per encryptionSP 800-38A requires unpredictable CBC IVs [5]
KeysSeparate AES and HMAC keysWe recommend never sharing a key between two algorithms
VerificationHMAC check before decryptionKeeps padding checks away from forged input; RFC 5246 records a timing attack on CBC padding [2]

Practical rules of thumb:

  • Generate a random 16-byte IV for every encryption; CBC requires unpredictable IVs, not just unique ones [5].
  • Always verify HMAC before decrypting. Never expose padding errors to attackers [2].
  • Use separate keys for AES and HMAC; derive both from a master key using HKDF if needed.
  • For new applications, prefer AES-GCM or ChaCha20-Poly1305. Each combines encryption and authentication in one specified construction [7][8].
Detailed Security Properties

Algorithm Details

  • Encryption: AES-CBC (128/192/256-bit keys) [5][6]
  • Authentication: HMAC-SHA256/SHA512
  • IV size: 128 bits (16 bytes) [5]
  • MAC size: 256 bits (32 bytes) or 512 bits (64 bytes)
  • Construction: Encrypt-then-MAC
  • Standards: TLS 1.2 CBC suites use MAC-then-encrypt by default [2]; RFC 7366 adds encrypt-then-MAC as a negotiated extension [3]

IV Management

IVs must be unpredictable [5]:

// CORRECT - Random IV per message
AutoSeededRandomPool rng;
byte iv[AES::BLOCKSIZE];
rng.GenerateBlock(iv, sizeof(iv));

// WRONG - Fixed IV (predictable)
static byte iv[AES::BLOCKSIZE] = {0};  // NEVER DO THIS

// WRONG - Reused IV
byte iv[AES::BLOCKSIZE] = {0};
// ... encrypt multiple messages with same IV ...  // NEVER DO THIS

SP 800-38A also allows an IV made by encrypting a unique nonce under the same key [5].

Encrypt-then-MAC vs MAC-then-Encrypt

// CORRECT - Encrypt-then-MAC
ciphertext = encrypt(plaintext)
mac = HMAC(IV || ciphertext)
send(IV || ciphertext || mac)

// WRONG - MAC-then-Encrypt
mac = HMAC(plaintext)
ciphertext = encrypt(plaintext || mac)  // the TLS 1.2 default record format

RFC 7366 describes MAC-then-encrypt as the subject of numerous security vulnerabilities and attacks over many years [3].

Security Best Practices

  1. Always Verify HMAC Before Decrypting:

    // CORRECT order
    if (!verifyHMAC(...)) {
        throw std::runtime_error("Authentication failed");
    }
    decrypt(...);  // Only if HMAC valid
    
    // WRONG order (padding errors become observable)
    decrypt(...);  // NEVER decrypt before HMAC verification
    if (!verifyHMAC(...)) { ... }
  2. Use Separate Keys:

    // CORRECT - separate keys
    SecByteBlock aesKey(16);
    SecByteBlock hmacKey(32);
    
    // WRONG - same key
    SecByteBlock key(16);
    // ... use for both AES and HMAC ...
    
  3. Include IV in HMAC:

    // CORRECT
    mac = HMAC(IV || ciphertext)
    
    // WRONG
    mac = HMAC(ciphertext)  // IV can be modified
    

    In CBC, a bit changed in the IV changes the same bit of the first decrypted block [5], so an unauthenticated IV lets an attacker edit the first block.

Thread Safety

Not thread-safe. Use separate instances per thread.

When to Use AES-CBC+HMAC

✅ Use AES-CBC+HMAC for:

  1. Legacy Compatibility - existing formats and systems built on CBC
  2. Compatibility - Systems without AES-GCM support

❌ Don’t use AES-CBC+HMAC for:

  1. New Applications - Use AES-GCM or ChaCha20-Poly1305 instead
  2. Simplicity - AEAD ciphers combine both steps in one object

NIST approves GCM and CCM as authenticated modes [7][9], so a NIST requirement is not a reason to choose CBC+HMAC.

AES-CBC+HMAC vs AES-GCM

FeatureCBC+HMACAES-GCM
API complexityHigherLower
ConstructionEncrypt-then-MACBuilt-in AEAD [7]
Encryption parallelizableNo (CBC) [5]Yes [7]
TLS 1.3Not available; TLS 1.3 uses only AEAD algorithms [10]Cipher suites defined [10]
PaddingRequired [5]None [7]
RecommendedLegacy onlyYes

Use AES-GCM for new applications. Use CBC+HMAC only for legacy compatibility.

Exceptions

  • InvalidCiphertext - Padding validation failed in StreamTransformationFilter (only reached after HMAC verification) [11]
  • The examples throw std::runtime_error on an HMAC mismatch. If you verify with HashVerificationFilter and THROW_EXCEPTION, a mismatch throws HashVerificationFilter::HashVerificationFailed [12]

See Also

References

  1. cryptopp-modern History.txt at 2026.11.0, release 2.1 (HMAC); line 456, release 3.1 (Rijndael); lines 521-530, release 5.0 (block cipher modes including CBC implement SymmetricCipher).
  2. RFC 5246: The Transport Layer Security (TLS) Protocol Version 1.2, sections 6.2.3.1 and 6.2.3.2.
  3. RFC 7366: Encrypt-then-MAC for TLS and DTLS, abstract and sections 1 and 3.
  4. misc.h at 2026.11.0, VerifyBufsEqual().
  5. NIST SP 800-38A: Recommendation for Block Cipher Modes of Operation, sections 5.3 and 6.2, appendices A, C and D.
  6. FIPS 197: Advanced Encryption Standard (AES), section 5, table 3.
  7. NIST SP 800-38D: Galois/Counter Mode (GCM) and GMAC, sections 3 and 5.2.1.2.
  8. RFC 8439: ChaCha20 and Poly1305 for IETF Protocols, section 2.8.
  9. NIST SP 800-38C: The CCM Mode for Authentication and Confidentiality, section 3.
  10. RFC 8446: The Transport Layer Security (TLS) Protocol Version 1.3, section 1.2 and appendix B.4.
  11. filters.cpp at 2026.11.0, InvalidCiphertext for invalid PKCS #7 padding.
  12. filters.h at 2026.11.0, HashVerificationFilter flags and HashVerificationFailed.