Skip to content

AES-CTR

Header: #include <cryptopp/aes.h>, #include <cryptopp/modes.h> | Namespace: CryptoPP Since: Crypto++ 3.1 (AES, as Rijndael); CTR mode is first listed in History.txt at 5.03 [1] Thread Safety: Not thread-safe per instance; use separate instances per thread

AES-CTR (Counter Mode) applies the AES forward cipher to a sequence of counter blocks and XORs the output with the plaintext. It provides confidentiality but not authentication [2]. You must add a MAC (like HMAC) or use an authenticated mode such as AES-GCM instead.

Important: CTR mode provides encryption only, not authentication. Flipping a bit in the ciphertext flips the same bit of the decrypted plaintext [2][3]. For most applications, use AES-GCM or ChaCha20-Poly1305 instead.

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 (use AES::MAX_KEYLENGTH for 256-bit)
    SecByteBlock key(AES::DEFAULT_KEYLENGTH);
    rng.GenerateBlock(key, key.size());

    // 16-byte IV (initial counter block); a fresh one for every message
    byte iv[AES::BLOCKSIZE];
    rng.GenerateBlock(iv, sizeof(iv));

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

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

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

    // Decrypt
    CTR_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

  • Make every counter block unique across all messages under a key [2]
  • Combine with HMAC for authenticated encryption (Encrypt-then-MAC)
  • Use for random-access decryption of data you also authenticate
  • Prefer AES-GCM for new applications needing authentication
  • CRITICAL: Never reuse a counter block with the same key [2]
  • Don’t use without authentication in network protocols
  • Don’t start every message at the same counter under one key
  • Don’t use for scenarios where authentication is needed

For storage devices, NIST approves XTS-AES (SP 800-38E), which the library provides as XTS_Mode in xts.h [4][5]. XTS does not authenticate the data either [4].

Why CTR Mode?

CTR mode has properties that make it useful for specific scenarios [2]:

PropertyBenefit
No paddingOutput size equals input size; the last block may be partial
Random accessAny block can be decrypted on its own if its counter block is known
ParallelizableEncryption and decryption can both be parallelized
Pre-computationKey stream can be generated before the plaintext is available
Same operationEncryption and decryption both use the forward cipher

In the library, CTR_Mode<AES>::Decryption is the same type as CTR_Mode<AES>::Encryption [6].

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 [7].

Constructors

// Default constructor (must call SetKeyWithIV)
CTR_Mode<AES>::Encryption enc;
CTR_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 initial counter value.

Parameters

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

The library increments the whole 16-byte counter block as a big-endian number [8].

ProcessData

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

Encrypts or decrypts data in place or to output buffer.

Seek

void Seek(lword position);

Seeks to a specific byte position in the key stream (for random access). CTR mode reports itself as random access [6][9].

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);
    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
    CTR_Mode<AES>::Encryption enc;
    enc.SetKeyWithIV(key, key.size(), iv);

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

    // Note: ciphertext.size() == plaintext.size() (no padding!)

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

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

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

    return 0;
}

Example 2: CTR with HMAC (Encrypt-then-MAC)

The MAC check uses HMAC::Verify(), which compares in constant time [10], instead of != on strings, which can return as soon as one byte differs.

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

using namespace CryptoPP;

class CtrThenHmac {
    SecByteBlock encKey;
    SecByteBlock macKey;

public:
    CtrThenHmac() {
        AutoSeededRandomPool rng;

        encKey.resize(AES::DEFAULT_KEYLENGTH);
        macKey.resize(32);  // HMAC-SHA256 key

        rng.GenerateBlock(encKey, encKey.size());
        rng.GenerateBlock(macKey, macKey.size());
    }

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

        // Fresh random initial counter block for every message
        byte iv[AES::BLOCKSIZE];
        rng.GenerateBlock(iv, sizeof(iv));

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

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

        // Prepend IV
        std::string result;
        result.assign((const char*)iv, sizeof(iv));
        result += ciphertext;

        // Compute HMAC over IV + ciphertext
        HMAC<SHA256> hmac(macKey, macKey.size());
        std::string mac;
        StringSource(result, true,
            new HashFilter(hmac,
                new StringSink(mac)
            )
        );

        // Append MAC
        result += mac;

        return result;  // IV || ciphertext || MAC
    }

    std::string decrypt(const std::string& data) {
        const size_t macSize = HMAC<SHA256>::DIGESTSIZE;
        if (data.size() < AES::BLOCKSIZE + macSize) {
            throw std::runtime_error("Data too short");
        }

        // Split: IV || ciphertext || MAC
        size_t macOffset = data.size() - macSize;
        std::string ivAndCiphertext = data.substr(0, macOffset);

        // Verify MAC first (Encrypt-then-MAC), in constant time
        HMAC<SHA256> hmac(macKey, macKey.size());
        hmac.Update((const byte*)ivAndCiphertext.data(), ivAndCiphertext.size());
        if (!hmac.Verify((const byte*)data.data() + macOffset)) {
            throw std::runtime_error("MAC verification failed");
        }

        // Extract IV and ciphertext
        byte iv[AES::BLOCKSIZE];
        std::memcpy(iv, ivAndCiphertext.data(), sizeof(iv));
        std::string ciphertext = ivAndCiphertext.substr(sizeof(iv));

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

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

        return plaintext;
    }
};

int main() {
    CtrThenHmac cipher;

    std::string plaintext = "Secret authenticated message";
    std::string encrypted = cipher.encrypt(plaintext);
    std::string decrypted = cipher.decrypt(encrypted);

    std::cout << "Original:  " << plaintext << std::endl;
    std::cout << "Decrypted: " << decrypted << std::endl;

    return 0;
}

The library also provides this pattern as a ready-made AEAD, AES-CTR-HMAC.

Example 3: Random Access Decryption

#include <cryptopp/aes.h>
#include <cryptopp/modes.h>
#include <cryptopp/osrng.h>
#include <iostream>
#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));

    // Encrypt a large block
    std::string plaintext(1000, 'A');
    for (size_t i = 0; i < plaintext.size(); i++) {
        plaintext[i] = 'A' + (i % 26);
    }

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

    std::string ciphertext(plaintext.size(), '\0');
    enc.ProcessData(reinterpret_cast<byte*>(&ciphertext[0]),
                    (const byte*)plaintext.data(),
                    plaintext.size());

    // Decrypt only bytes 500-509 (random access!)
    CTR_Mode<AES>::Decryption dec;
    dec.SetKeyWithIV(key, key.size(), iv);

    // Seek to position 500
    dec.Seek(500);

    byte decrypted[10];
    dec.ProcessData(decrypted, (const byte*)ciphertext.data() + 500, 10);

    std::cout << "Decrypted bytes 500-509: ";
    std::cout.write((const char*)decrypted, 10);
    std::cout << std::endl;

    // Verify against original
    std::cout << "Original bytes 500-509:  ";
    std::cout << plaintext.substr(500, 10) << std::endl;

    return 0;
}

Example 4: File Encryption

This example only encrypts; nothing detects a modified file, and decryption writes whatever the ciphertext decrypts to. For files, prefer the AES-GCM file example, which verifies the tag before writing the output.

#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
    CTR_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
    CTR_Mode<AES>::Decryption dec;
    dec.SetKeyWithIV(key, key.size(), iv);

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

Example 5: In-Place Encryption

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

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 buffer
    std::vector<byte> data = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'};

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

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

    std::cout << "Encrypted (hex): ";
    for (byte b : data) {
        std::printf("%02X", b);
    }
    std::cout << std::endl;

    // Decrypt in place
    CTR_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;
}

IV/Nonce Requirements

Critical: Never Reuse a Counter Block with the Same Key

If two messages use the same counter block T under the same key:
- keystream block O = AES(key, T) is the same for both
- C1 XOR C2 = P1 XOR P2 for those blocks

Anyone who knows one of the plaintext blocks can recover the other.

SP 800-38A requires every counter block to be unique across all messages encrypted under a key, and explains that a repeated counter block exposes the plaintext as shown above [2].

Safe IV Generation

// Option 1: Random initial counter block per message
AutoSeededRandomPool rng;
byte iv[AES::BLOCKSIZE];
rng.GenerateBlock(iv, sizeof(iv));

// Option 2: SP 800-38A Appendix B.2 layout:
// 64-bit message number || 64-bit block counter starting at 0.
// The message number must never repeat under this key.
word64 messageNumber = nextMessageNumber();   // your persistent counter
byte iv2[AES::BLOCKSIZE] = {0};
PutWord(false, BIG_ENDIAN_ORDER, iv2, messageNumber);   // from misc.h

The library declares CTR’s IV requirement as RANDOM_IV [6]. Option 2 follows the second approach in SP 800-38A Appendix B.2: a unique message nonce in the leading half of the counter block and a block index in the rest [2]. Because the library increments the whole 16-byte block [8], the counter blocks of one message stay within its message number as long as the message is shorter than 2^64 blocks.

Do not use a random value per session with a counter that restarts at zero for each message: every message would then use the same counter blocks.

CTR Mode vs Other Modes

FeatureCTRCBCGCM
PaddingNo [2]Yes [2]No [3]
Encrypt parallelYes [2]No [2]Yes [3]
Decrypt parallelYes [2]Yes [2]Yes [3]
AuthenticationNoNoYes [3]
IV requirementUnique counter blocks [2]Unpredictable IV [2]Unique IV [3]

Performance

SP 800-38A notes that CTR encryption and decryption can be parallelized and that the keystream can be computed before the data arrives [2].

Security Properties

PropertyValue
ConfidentialityYes, while counter blocks never repeat under the key [2]
IntegrityNo (must add MAC) [2]
Key size128, 192, or 256 bits [11]
Block size128 bits [11]
Counter blocksUnique across all messages under a key [2]

Security Notes

  1. No authentication: Ciphertext can be modified undetected
  2. Bit-flipping attacks: A bit flipped in the ciphertext flips the same plaintext bit [2][3]
  3. Counter uniqueness: Each counter block must be used only once per key [2]

When to Use CTR Mode

✅ Use CTR for:

  1. Random access requirements (seek to any position) [2]
  2. Streaming encryption where length is unknown
  3. When combined with HMAC (Encrypt-then-MAC)
  4. Building custom AEAD constructions

❌ Don’t use CTR alone for:

  1. Network protocols (use GCM or ChaCha20-Poly1305)
  2. Any scenario needing integrity without adding MAC
  3. When simpler authenticated modes are available
  4. Storage devices, where XTS-AES is the NIST-approved mode [4]

Thread Safety

CTR mode objects are not thread-safe:

// WRONG - shared instance
CTR_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));

    CTR_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 safeCTR(const CryptoPP::SecByteBlock& key, const CryptoPP::byte* iv,
             const std::string& plaintext) {
    using namespace CryptoPP;

    try {
        CTR_Mode<AES>::Encryption enc;
        enc.SetKeyWithIV(key, key.size(), iv);

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

    } catch (const InvalidKeyLength& e) {
        std::cerr << "Invalid key length: " << e.what() << std::endl;
        // AES requires 16, 24, or 32 byte keys
    } catch (const Exception& e) {
        std::cerr << "Encryption error: " << e.what() << std::endl;
    }
}

See Also

References

  1. cryptopp-modern History.txt at 2026.11.0, release 3.1 (Rijndael), and lines 545-546, release 5.03 (first entry that mentions CTR mode).
  2. NIST SP 800-38A: Recommendation for Block Cipher Modes of Operation, sections 5.3, 6.2 and 6.5, appendices A, B and D.
  3. NIST SP 800-38D: Galois/Counter Mode (GCM) and GMAC, section 3, section 8 and appendix A.
  4. NIST SP 800-38E: The XTS-AES Mode for Confidentiality on Storage Devices, abstract.
  5. xts.h at 2026.11.0, XTS mode and the XTS_Mode alias.
  6. modes.h at 2026.11.0, CTR_ModePolicy (random access, RANDOM_IV), and lines 516-519, CTR_Mode with Decryption the same as Encryption.
  7. rijndael.h at 2026.11.0, Rijndael_Info: 16-byte block, keys of 16 to 32 bytes in steps of 8.
  8. modes.cpp at 2026.11.0 and misc.h, the counter is incremented across the whole block.
  9. cryptlib.h at 2026.11.0, IsRandomAccess() and Seek().
  10. cryptlib.h at 2026.11.0, Verify() compares with VerifyBufsEqual(), a constant-time comparison.
  11. FIPS 197: Advanced Encryption Standard (AES), section 5, table 3.