Skip to content

AES-CBC

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

AES-CBC (Cipher Block Chaining) is a block cipher mode that XORs each plaintext block with the previous ciphertext block before encryption. It provides confidentiality but not authentication [2].

Important: CBC mode provides encryption only, not authentication. RFC 5246 records a timing attack on CBC padding and requires TLS 1.2 receivers to treat padding errors exactly like MAC failures [3]. For authenticated encryption, use AES-GCM or AES-CBC with HMAC.

Quick Example

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

int main() {
    using namespace CryptoPP;

    AutoSeededRandomPool rng;

    // 128-bit key
    SecByteBlock key(AES::DEFAULT_KEYLENGTH);
    rng.GenerateBlock(key, key.size());

    // 16-byte random IV, new for every message
    byte iv[AES::BLOCKSIZE];
    rng.GenerateBlock(iv, sizeof(iv));

    std::string plaintext = "Secret message";
    std::string ciphertext, recovered;

    // Encrypt (PKCS #7 padding applied automatically)
    CBC_Mode<AES>::Encryption enc;
    enc.SetKeyWithIV(key, key.size(), iv);

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

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

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

    std::cout << "Recovered: " << recovered << std::endl;
    return 0;
}

Usage Guidelines

  • Use an unpredictable IV for every message, such as 16 random bytes from AutoSeededRandomPool [2]
  • Always combine with HMAC for authenticated encryption (Encrypt-then-MAC)
  • Use PKCS #7 padding (the default for CBC in Crypto++) [4]
  • Verify the MAC before decrypting
  • CRITICAL: Never reuse an IV with the same key
  • Don’t use without authentication in any real application
  • Don’t expose padding errors separately from authentication errors [3]
  • Don’t use for new designs when GCM is available

How CBC Works

Encryption:
C[1] = AES(key, P[1] XOR IV)
C[i] = AES(key, P[i] XOR C[i-1])    for i = 2 ... n

Decryption:
P[1] = AES_inverse(key, C[1]) XOR IV
P[i] = AES_inverse(key, C[i]) XOR C[i-1]

Each encryption step depends on the previous ciphertext block, so encryption cannot be parallelized; decryption can, because all ciphertext blocks are available [2].

Constants

AES::DEFAULT_KEYLENGTH    // 16 bytes (128-bit)
AES::MAX_KEYLENGTH        // 32 bytes (256-bit)
AES::BLOCKSIZE            // 16 bytes (IV size)

These are the Rijndael_Info values [5].

Constructors

// Default constructor (must call SetKeyWithIV)
CBC_Mode<AES>::Encryption enc;
CBC_Mode<AES>::Decryption dec;

Methods

SetKeyWithIV

void SetKeyWithIV(const byte* key, size_t keyLen, const byte* iv, size_t ivLen = BLOCKSIZE);

Sets the encryption/decryption key and initialization vector. The library declares CBC’s IV requirement as UNPREDICTABLE_RANDOM_IV [6].

Parameters

ParameterTypeDescription
keyconst byte*Encryption key (16, 24, or 32 bytes)
keyLensize_tKey length in bytes
ivconst byte*Initialization vector (16 bytes)
ivLensize_tIV length (default: block size)

ProcessData

void ProcessData(byte* outString, const byte* inString, size_t length);

Processes data. For CBC, length must be a multiple of block size (use StreamTransformationFilter for automatic padding) [2].

Complete Examples

Example 1: Basic Encryption/Decryption

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

int main() {
    using namespace CryptoPP;

    AutoSeededRandomPool rng;

    // Generate key and IV
    SecByteBlock key(AES::DEFAULT_KEYLENGTH);  // 128-bit
    rng.GenerateBlock(key, key.size());

    byte iv[AES::BLOCKSIZE];
    rng.GenerateBlock(iv, sizeof(iv));

    std::string plaintext = "The quick brown fox jumps over the lazy dog";
    std::string ciphertext, recovered;

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

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

    // Note: ciphertext is padded to multiple of 16 bytes
    std::cout << "Plaintext size:  " << plaintext.size() << std::endl;
    std::cout << "Ciphertext size: " << ciphertext.size() << std::endl;

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

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

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

    return 0;
}

Example 2: AES-256-CBC

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

int main() {
    using namespace CryptoPP;

    AutoSeededRandomPool rng;

    // 256-bit key
    SecByteBlock key(AES::MAX_KEYLENGTH);  // 32 bytes
    rng.GenerateBlock(key, key.size());

    byte iv[AES::BLOCKSIZE];
    rng.GenerateBlock(iv, sizeof(iv));

    std::string plaintext = "High security message";
    std::string ciphertext, recovered;

    // Encrypt with AES-256
    CBC_Mode<AES>::Encryption enc;
    enc.SetKeyWithIV(key, key.size(), iv);

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

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

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

    return 0;
}

Example 3: File Encryption

This example only encrypts. Nothing detects a modified file, and decryption writes its output as it goes. For files, use the AES-CBC with HMAC file example, which checks the MAC before decrypting, or AES-GCM.

#include <cryptopp/aes.h>
#include <cryptopp/modes.h>
#include <cryptopp/files.h>
#include <cryptopp/filters.h>
#include <cryptopp/osrng.h>
#include <fstream>

void encryptFile(const std::string& inputFile,
                 const std::string& outputFile,
                 const CryptoPP::SecByteBlock& key) {
    using namespace CryptoPP;

    AutoSeededRandomPool rng;

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

    // Write IV first
    std::ofstream out(outputFile, std::ios::binary);
    out.write((const char*)iv, sizeof(iv));

    // Encrypt file
    CBC_Mode<AES>::Encryption enc;
    enc.SetKeyWithIV(key, key.size(), iv);

    FileSource(inputFile.c_str(), true,
        new StreamTransformationFilter(enc,
            new FileSink(out)
        )
    );
}

void decryptFile(const std::string& inputFile,
                 const std::string& outputFile,
                 const CryptoPP::SecByteBlock& key) {
    using namespace CryptoPP;

    // Read IV
    std::ifstream in(inputFile, std::ios::binary);
    byte iv[AES::BLOCKSIZE];
    if (!in.read(reinterpret_cast<char*>(iv), sizeof(iv)))
        throw Exception(Exception::INVALID_DATA_FORMAT, "encrypted file is too short");

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

    FileSource(in, true,
        new StreamTransformationFilter(dec,
            new FileSink(outputFile.c_str())
        )
    );
}

Example 4: Manual Padding Control

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

int main() {
    using namespace CryptoPP;

    AutoSeededRandomPool rng;

    SecByteBlock key(AES::DEFAULT_KEYLENGTH);
    rng.GenerateBlock(key, key.size());

    byte iv[AES::BLOCKSIZE];
    rng.GenerateBlock(iv, sizeof(iv));

    std::string plaintext = "Test";
    std::string ciphertext, recovered;

    // Encrypt with explicit padding mode
    CBC_Mode<AES>::Encryption enc;
    enc.SetKeyWithIV(key, key.size(), iv);

    // PKCS_PADDING is default, but can be explicit
    StringSource(plaintext, true,
        new StreamTransformationFilter(enc,
            new StringSink(ciphertext),
            StreamTransformationFilter::PKCS_PADDING
        )
    );

    // For data already padded or exact block size multiples:
    // StreamTransformationFilter::NO_PADDING

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

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

    return 0;
}

Example 5: In-Place Encryption (Block-Aligned Data)

#include <cryptopp/aes.h>
#include <cryptopp/modes.h>
#include <cryptopp/osrng.h>
#include <iostream>
#include <vector>
#include <cstring>

int main() {
    using namespace CryptoPP;

    AutoSeededRandomPool rng;

    SecByteBlock key(AES::DEFAULT_KEYLENGTH);
    rng.GenerateBlock(key, key.size());

    byte iv[AES::BLOCKSIZE];
    rng.GenerateBlock(iv, sizeof(iv));

    // Data must be multiple of block size for raw ProcessData
    std::vector<byte> data(32);  // 2 blocks
    memcpy(data.data(), "Hello World!1234Hello World!1234", 32);

    std::cout << "Original: ";
    std::cout.write((const char*)data.data(), data.size());
    std::cout << std::endl;

    // Encrypt in place
    CBC_Mode<AES>::Encryption enc;
    enc.SetKeyWithIV(key, key.size(), iv);
    enc.ProcessData(data.data(), data.data(), data.size());

    // Decrypt in place
    CBC_Mode<AES>::Decryption dec;
    dec.SetKeyWithIV(key, key.size(), iv);
    dec.ProcessData(data.data(), data.data(), data.size());

    std::cout << "Decrypted: ";
    std::cout.write((const char*)data.data(), data.size());
    std::cout << std::endl;

    return 0;
}

Padding

CBC mode requires the plaintext to be a whole number of blocks [2]. For CBC, DEFAULT_PADDING in StreamTransformationFilter means PKCS_PADDING [4], the PKCS #7 padding that RFC 5652 describes [7]:

Original: "Hello" (5 bytes)
Padded:   "Hello\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b" (16 bytes)

Padding byte value = number of padding bytes added (1 to 16)

Every input is padded, including input that is already a multiple of the block size, so the padding can be removed unambiguously [7].

Padding Options

// PKCS #7 padding (default for CBC)
StreamTransformationFilter::PKCS_PADDING

// No padding (data must be block-aligned)
StreamTransformationFilter::NO_PADDING

// Zero padding
StreamTransformationFilter::ZEROS_PADDING

// One-and-zeros padding
StreamTransformationFilter::ONE_AND_ZEROS_PADDING

// W3C XML Encryption padding
StreamTransformationFilter::W3C_PADDING

These are the BlockPaddingScheme values [4]. We do not recommend ZEROS_PADDING: trailing zero bytes in the plaintext cannot be told apart from the padding.

Padding Oracle Attacks

RFC 5246 describes a timing attack on CBC padding and requires TLS 1.2 receivers to report padding errors with the same alert as MAC failures and to spend the same time either way [3]. A decryptor that lets an attacker tell padding errors apart from other failures is at risk.

Mitigation: Use Encrypt-then-MAC and verify the MAC before decrypting. See AES-CBC with HMAC.

// WRONG - Leaks padding information
try {
    // Decrypt
} catch (const InvalidCiphertext& e) {
    return "Padding error";  // Padding oracle!
}

// CORRECT - Verify MAC first, generic error
if (!verifyHMAC(ciphertext, mac)) {
    return "Authentication failed";  // No padding info leaked
}
// Only then decrypt

StreamTransformationFilter throws InvalidCiphertext when it finds invalid PKCS #7 padding [8].

IV Requirements

The IV Must Be Unpredictable

SP 800-38A requires the CBC IV to be unpredictable, not just unique, and gives two methods: encrypt a unique nonce under the same key, or generate a random block with an approved random number generator [2].

With a repeated IV, two messages that share leading plaintext blocks also share leading ciphertext blocks; this follows from the formulas above.

Safe IV Generation

// Always use cryptographically random IV
AutoSeededRandomPool rng;
byte iv[AES::BLOCKSIZE];
rng.GenerateBlock(iv, sizeof(iv));

// Store/transmit IV with ciphertext (IV is not secret)

The IV need not be secret and may be sent with the ciphertext [2].

CBC vs Other Modes

FeatureCBCCTRGCM
PaddingYes [2]No [2]No [9]
Encrypt parallelNo [2]Yes [2]Yes [9]
Decrypt parallelYes [2]Yes [2]Yes [9]
AuthenticationNoNoYes [9]
IV requirementUnpredictable [2]Unique counter blocks [2]Unique [9]

Performance

CBC encryption is sequential and CBC decryption can be parallelized [2].

Security Properties

PropertyValue
ConfidentialityYes, with an unpredictable IV [2]
IntegrityNo (must add MAC) [2]
Key size128, 192, or 256 bits [10]
Block size128 bits [10]
IV size128 bits [2][10]

When to Use CBC

✅ Use CBC for:

  1. Legacy compatibility with existing CBC-based systems
  2. Combined with HMAC (Encrypt-then-MAC) when GCM unavailable

For storage devices, NIST approves XTS-AES (SP 800-38E), which the library provides as XTS_Mode in xts.h [11][12].

❌ Don’t use CBC alone for:

  1. New applications (use GCM or ChaCha20-Poly1305)
  2. Network protocols without authentication
  3. Any scenario where padding errors might be observable [3]

Thread Safety

CBC mode objects are not thread-safe:

// WRONG - shared instance
CBC_Mode<AES>::Encryption sharedEnc;

// CORRECT - per-thread
void encryptInThread(const std::string& plaintext,
                     const SecByteBlock& key) {
    AutoSeededRandomPool rng;
    byte iv[AES::BLOCKSIZE];
    rng.GenerateBlock(iv, sizeof(iv));

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

    std::string ciphertext;
    StringSource(plaintext, true,
        new StreamTransformationFilter(enc,
            new StringSink(ciphertext)
        )
    );
}

Error Handling

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

void safeCBC(const CryptoPP::SecByteBlock& key, const CryptoPP::byte* iv,
             const std::string& ciphertext) {
    using namespace CryptoPP;

    try {
        CBC_Mode<AES>::Decryption dec;
        dec.SetKeyWithIV(key, key.size(), iv);

        std::string plaintext;
        StringSource(ciphertext, true,
            new StreamTransformationFilter(dec,
                new StringSink(plaintext)
            )
        );

    } catch (const InvalidKeyLength& e) {
        std::cerr << "Invalid key length" << std::endl;

    } catch (const InvalidCiphertext& e) {
        // CAREFUL: Don't leak this as distinct from MAC failure
        // In production, verify MAC first!
        std::cerr << "Decryption failed" << std::endl;

    } catch (const Exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }
}

See Also

References

  1. cryptopp-modern History.txt at 2026.11.0, release 3.1 (Rijndael), and lines 521-530, release 5.0 (SymmetricCipher implemented by block cipher modes including CBC; AES::Encryption naming).
  2. NIST SP 800-38A: Recommendation for Block Cipher Modes of Operation, sections 5.3, 6.2 and 6.5, appendices A, B and C.
  3. RFC 5246: The Transport Layer Security (TLS) Protocol Version 1.2, section 6.2.3.2.
  4. filters.h at 2026.11.0, BlockPaddingScheme and the meaning of DEFAULT_PADDING.
  5. rijndael.h at 2026.11.0, Rijndael_Info: 16-byte block, keys of 16 to 32 bytes in steps of 8.
  6. modes.h at 2026.11.0, CBC_ModeBase IV requirement.
  7. RFC 5652: Cryptographic Message Syntax (CMS), section 6.3.
  8. filters.cpp at 2026.11.0, InvalidCiphertext for bad length or invalid PKCS #7 padding.
  9. NIST SP 800-38D: Galois/Counter Mode (GCM) and GMAC, sections 3 and 8.
  10. FIPS 197: Advanced Encryption Standard (AES), section 5, table 3.
  11. NIST SP 800-38E: The XTS-AES Mode for Confidentiality on Storage Devices, abstract.
  12. xts.h at 2026.11.0, XTS mode and the XTS_Mode alias.