Skip to content

ChaCha20-Poly1305

Header: #include <cryptopp/chachapoly.h> | Namespace: CryptoPP Since: Crypto++ 8.1 [1] Thread Safety: Not thread-safe per instance; use separate instances per thread

ChaCha20-Poly1305 is the authenticated encryption with associated data (AEAD) construction from RFC 8439. It combines the ChaCha20 stream cipher with the Poly1305 authenticator [2][3]. RFC 8439 describes ChaCha20 as around three times as fast as AES on platforms that lack specialized AES hardware [2].

The nonce must never repeat under a key, and RFC 8439 says it must not be generated randomly; use a counter [2]. If you want random nonces, use XChaCha20-Poly1305 or XAES-256-GCM instead.

Quick Example

#include <cryptopp/chachapoly.h>
#include <cryptopp/filters.h>
#include <cryptopp/misc.h>
#include <cryptopp/osrng.h>
#include <iostream>

int main() {
    using namespace CryptoPP;

    AutoSeededRandomPool rng;

    // 256-bit key
    SecByteBlock key(32);
    rng.GenerateBlock(key, key.size());

    // 96-bit nonce built from a message counter. The counter must never
    // repeat under this key, so store it with the key between runs.
    word64 messageNumber = 1;
    byte nonce[12] = {0};
    PutWord(false, BIG_ENDIAN_ORDER, nonce + 4, messageNumber);

    // Encrypt with authentication
    ChaCha20Poly1305::Encryption enc;
    enc.SetKeyWithIV(key, key.size(), nonce, sizeof(nonce));

    std::string plaintext = "Secret message";
    std::string ciphertext;  // AuthenticatedEncryptionFilter appends the tag

    AuthenticatedEncryptionFilter ef(enc,
        new StringSink(ciphertext),
        false, 16
    );

    ef.Put((const byte*)plaintext.data(), plaintext.size());
    ef.MessageEnd();

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

    // Decrypt and verify
    ChaCha20Poly1305::Decryption dec;
    dec.SetKeyWithIV(key, key.size(), nonce, sizeof(nonce));

    std::string recovered;
    AuthenticatedDecryptionFilter df(dec,
        new StringSink(recovered)
    );

    df.Put((const byte*)ciphertext.data(), ciphertext.size());
    df.MessageEnd();

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

    return 0;
}

Usage Guidelines

Do:

  • Use a 12-byte nonce that is unique for every message under a key; a counter is the method RFC 8439 suggests [2]
  • Keep the counter state with the key so that a restart cannot reuse a nonce
  • Include associated data (AAD) for metadata that must be authenticated
  • Use XChaCha20-Poly1305 when you want random nonces

Avoid:

  • Random 12-byte nonces; RFC 8439 says the nonce must not be randomly generated
  • Reusing a nonce with the same key, which reveals the XOR of the plaintexts [2]
  • Using the plaintext before the tag has been verified

Class: ChaCha20Poly1305::Encryption

Encrypt and authenticate data.

Constants

Key size:  32 bytes (256-bit)
IV size:   12 bytes (96-bit nonce)
Tag size:  16 bytes (128-bit)

The library accepts only a 32-byte key and only a 12-byte nonce, and its full tag is 16 bytes [4]. RFC 8439 specifies the same sizes [2].

Methods

SetKeyWithIV()

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

Initialise with key and nonce.

Parameters:

  • key - Secret key (32 bytes)
  • keyLen - Key length (must be 32)
  • iv - Nonce (12 bytes)
  • ivLen - Nonce length (must be 12)

Example:

SecByteBlock key(32);
rng.GenerateBlock(key, key.size());

byte nonce[12] = {0};
PutWord(false, BIG_ENDIAN_ORDER, nonce + 4, messageNumber);  // word64 counter

ChaCha20Poly1305::Encryption enc;
enc.SetKeyWithIV(key, key.size(), nonce, sizeof(nonce));

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 for encrypted data
  • mac - Output buffer for authentication tag (16 bytes)
  • macSize - Tag size. Use 16. RFC 8439 requires the complete tag: “Tag truncation MUST NOT be done” [2]. The library accepts smaller values [4], but a truncated tag is not the RFC 8439 construction
  • iv - Nonce
  • ivLength - Nonce length
  • aad - Associated data (can be NULL)
  • aadLength - AAD length
  • message - Plaintext to encrypt
  • messageLength - Plaintext length

Example:

ChaCha20Poly1305::Encryption enc;
enc.SetKeyWithIV(key, key.size(), nonce, sizeof(nonce));

std::string plaintext = "Secret data";
std::string aad = "User: Alice";

byte ciphertext[1024];
byte tag[16];

enc.EncryptAndAuthenticate(
    ciphertext, tag, sizeof(tag),
    nonce, sizeof(nonce),
    (const byte*)aad.data(), aad.size(),
    (const byte*)plaintext.data(), plaintext.size()
);

Class: ChaCha20Poly1305::Decryption

Decrypt and verify authentication.

Methods

SetKeyWithIV()

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

Initialise with key and nonce (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 verification.

Returns: true if authentication succeeded, false if tag mismatch [4]

Example:

ChaCha20Poly1305::Decryption dec;
dec.SetKeyWithIV(key, key.size(), nonce, sizeof(nonce));

byte recovered[1024];

bool valid = dec.DecryptAndVerify(
    recovered,
    tag, sizeof(tag),
    nonce, sizeof(nonce),
    (const byte*)aad.data(), aad.size(),
    ciphertext, ciphertextLength
);

if (!valid) {
    std::cerr << "Authentication failed!" << std::endl;
    // DO NOT use decrypted data
}

Complete Example: Secure Messaging with AAD

The sender numbers its messages and builds each nonce from that number, so no nonce repeats under the key.

#include <cryptopp/chachapoly.h>
#include <cryptopp/osrng.h>
#include <cryptopp/filters.h>
#include <cryptopp/misc.h>
#include <cstring>
#include <iostream>
#include <stdexcept>

using namespace CryptoPP;

struct SecureMessage {
    byte nonce[12];
    std::string ciphertext;

    // messageNumber must never repeat under the same key
    std::string encrypt(const SecByteBlock& key,
                        word64 messageNumber,
                        const std::string& plaintext,
                        const std::string& metadata) {
        std::memset(nonce, 0, sizeof(nonce));
        PutWord(false, BIG_ENDIAN_ORDER, nonce + 4, messageNumber);

        // Encrypt with metadata as AAD
        ChaCha20Poly1305::Encryption enc;
        enc.SetKeyWithIV(key, key.size(), nonce, sizeof(nonce));

        AuthenticatedEncryptionFilter ef(enc,
            new StringSink(ciphertext),
            false, 16
        );

        // Add AAD (metadata)
        ef.ChannelPut(AAD_CHANNEL, (const byte*)metadata.data(),
                      metadata.size());
        ef.ChannelMessageEnd(AAD_CHANNEL);

        // Encrypt plaintext
        ef.ChannelPut(DEFAULT_CHANNEL, (const byte*)plaintext.data(),
                      plaintext.size());
        ef.ChannelMessageEnd(DEFAULT_CHANNEL);

        return ciphertext;
    }

    std::string decrypt(const SecByteBlock& key,
                        const std::string& metadata) {
        ChaCha20Poly1305::Decryption dec;
        dec.SetKeyWithIV(key, key.size(), nonce, sizeof(nonce));

        std::string recovered;
        AuthenticatedDecryptionFilter df(dec,
            new StringSink(recovered),
            AuthenticatedDecryptionFilter::DEFAULT_FLAGS
        );

        // Add AAD (must match encryption)
        df.ChannelPut(AAD_CHANNEL, (const byte*)metadata.data(),
                      metadata.size());
        df.ChannelMessageEnd(AAD_CHANNEL);

        // Decrypt ciphertext
        try {
            df.ChannelPut(DEFAULT_CHANNEL, (const byte*)ciphertext.data(),
                          ciphertext.size());
            df.ChannelMessageEnd(DEFAULT_CHANNEL);
        } catch (const HashVerificationFilter::HashVerificationFailed&) {
            throw std::runtime_error("Authentication failed!");
        }

        return recovered;
    }
};

int main() {
    AutoSeededRandomPool rng;

    // Generate shared key
    SecByteBlock key(32);
    rng.GenerateBlock(key, key.size());

    // Create message
    SecureMessage msg;
    std::string plaintext = "Transfer $1000 to Bob";
    std::string metadata = "From: Alice, To: Bob, Timestamp: 2024-11-26";

    // Encrypt message number 1 under this key
    std::string ciphertext = msg.encrypt(key, 1, plaintext, metadata);
    std::cout << "Encrypted: " << ciphertext.size() << " bytes" << std::endl;

    // Decrypt
    try {
        std::string recovered = msg.decrypt(key, metadata);
        std::cout << "Decrypted: " << recovered << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }

    // Try with wrong metadata (will fail)
    try {
        std::string wrong_metadata = "From: Eve, To: Bob, Timestamp: 2024-11-26";
        std::string recovered = msg.decrypt(key, wrong_metadata);
        std::cout << "This should not print!" << std::endl;
    } catch (const std::exception& e) {
        std::cout << "Authentication correctly failed with wrong AAD" << std::endl;
    }

    return 0;
}

Complete Example: File Encryption

AuthenticatedDecryptionFilter passes decrypted data to its attachment before it checks the tag at the end of the message [5], so this example decrypts into memory and writes the output file only after the tag has been verified. The caller supplies a file number that must never repeat under the key; if you cannot keep that state, use XChaCha20-Poly1305 with a random nonce.

#include <cryptopp/chachapoly.h>
#include <cryptopp/osrng.h>
#include <cryptopp/files.h>
#include <cryptopp/filters.h>
#include <cryptopp/misc.h>
#include <iostream>

using namespace CryptoPP;

void encryptFile(const std::string& inputFile,
                 const std::string& outputFile,
                 const SecByteBlock& key,
                 word64 fileNumber) {
    // Nonce from a counter that is never reused under this key
    byte nonce[12] = {0};
    PutWord(false, BIG_ENDIAN_ORDER, nonce + 4, fileNumber);

    // Write nonce to output file first
    FileSink outFile(outputFile.c_str());
    outFile.Put(nonce, sizeof(nonce));

    // Encrypt file; output is ciphertext || tag
    ChaCha20Poly1305::Encryption enc;
    enc.SetKeyWithIV(key, key.size(), nonce, sizeof(nonce));

    FileSource(inputFile.c_str(), true,
        new AuthenticatedEncryptionFilter(enc,
            new Redirector(outFile),
            false, 16
        )
    );

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

bool decryptFile(const std::string& inputFile,
                 const std::string& outputFile,
                 const SecByteBlock& key) {
    // Read the whole encrypted file
    std::string encrypted;
    FileSource(inputFile.c_str(), true, new StringSink(encrypted));

    const size_t nonceSize = 12, tagSize = 16;
    if (encrypted.size() < nonceSize + tagSize) {
        std::cerr << "File too short" << std::endl;
        return false;
    }

    const byte* nonce = (const byte*)encrypted.data();

    ChaCha20Poly1305::Decryption dec;
    dec.SetKeyWithIV(key, key.size(), nonce, nonceSize);

    // Decrypt into memory; nothing is written to disk yet
    std::string recovered;
    try {
        StringSource(encrypted.substr(nonceSize), true,
            new AuthenticatedDecryptionFilter(dec,
                new StringSink(recovered)
            )
        );
    } catch (const HashVerificationFilter::HashVerificationFailed&) {
        std::cerr << "Authentication failed! File may be corrupted." << std::endl;
        return false;
    }

    // The tag verified, so the plaintext can be written
    StringSource(recovered, true, new FileSink(outputFile.c_str()));
    std::cout << "File decrypted: " << outputFile << std::endl;
    return true;
}

int main() {
    AutoSeededRandomPool rng;

    // Generate key
    SecByteBlock key(32);
    rng.GenerateBlock(key, key.size());

    // Encrypt file number 1 under this key
    encryptFile("document.pdf", "document.pdf.enc", key, 1);

    // Decrypt file
    decryptFile("document.pdf.enc", "document_decrypted.pdf", key);

    return 0;
}

Performance

RFC 8439 states that ChaCha20 is considerably faster than AES in software-only implementations, around three times as fast on platforms without specialized AES hardware [2].

Security

Quick Summary

AspectValueSource
Key size256-bit (32 bytes) onlyRFC 8439 [2], library [4]
Nonce12 bytes, unique per message under a key, not randomRFC 8439 [2]
Tag length128-bit tag (16 bytes)RFC 8439 [2]
Maximum plaintext per nonce274,877,906,880 bytes (nearly 256 GB)RFC 8439 [2], library [4]
Forgery boundForgeries rejected with probability 1-(n/2^102) for a 16n-byte messageRFC 8439 [2]

Practical rules of thumb:

  • Use a counter for the nonce; RFC 8439 names counters and LFSRs as acceptable ways to generate unique nonces [2].
  • Always verify the authentication tag; treat any verification failure as a hard error and discard the output.
  • If you need random nonces, use XChaCha20-Poly1305, whose 24-byte nonce is intended for random generation [6].
Detailed Security Properties

Algorithm Details

  • Encryption: ChaCha20 stream cipher (256-bit key) [2]
  • Authentication: Poly1305 (128-bit tag) [2]
  • Nonce size: 96 bits (12 bytes) [2][4]
  • Key size: 256 bits (32 bytes) only [2][4]
  • Tag size: 128 bits (16 bytes) [2][4]
  • Specification: RFC 8439 section 2.8 [2]

Nonce Management

CRITICAL: Never reuse nonces with the same key.

// CORRECT - counter-based nonces: 4 zero bytes || 64-bit message counter
word64 counter = 0;   // persist this with the key
for (int i = 0; i < 100; i++) {
    byte nonce[12] = {0};
    PutWord(false, BIG_ENDIAN_ORDER, nonce + 4, counter);
    counter++;
    // ... encrypt with unique nonce ...
}

// CATASTROPHIC - Nonce reuse
byte nonce[12] = {0};  // Same nonce!
// ... encrypt multiple messages ...  // NEVER DO THIS

WireGuard also builds its nonces from 32 zero bits followed by a 64-bit counter, which it encodes little-endian [7].

Nonce reuse consequences: if a nonce repeats, the one-time Poly1305 key and the keystream are the same for both messages, which reveals the XOR of the plaintexts [2].

Security Best Practices

  1. Never Reuse Nonces:

    • Use a counter or another scheme that guarantees uniqueness under the key
    • Do not generate 12-byte nonces randomly [2]
    • Switch to XChaCha20-Poly1305 if a counter cannot be maintained
  2. Authenticate-then-Decrypt:

    // Authentication happens automatically in DecryptionFilter
    try {
        df.Put(ciphertext, size);
        df.MessageEnd();
        // Authentication succeeded - safe to use plaintext
    } catch (const HashVerificationFilter::HashVerificationFailed&) {
        // Authentication failed - DO NOT use plaintext
    }

    The filter has already passed decrypted bytes to its attachment when the exception is thrown [5], so attach it to a buffer you discard on failure, not to a file or socket.

  3. Use AAD for Metadata:

    // Include message headers, timestamps, etc. as AAD
    std::string aad = "From: Alice, To: Bob, ID: 12345";
    // AAD is authenticated but not encrypted
    

Thread Safety

Not thread-safe. Use separate instances per thread.

When to Use ChaCha20-Poly1305

✅ Use ChaCha20-Poly1305 for:

  1. Systems without AES hardware - RFC 8439 gives ChaCha20 a speed advantage there [2]
  2. Constant-time implementations - ChaCha20 and Poly1305 were designed to be easy to implement in constant time [2]
  3. TLS 1.3 - TLS_CHACHA20_POLY1305_SHA256 is a TLS 1.3 cipher suite [8]
  4. Protocols with message counters - the counter supplies the nonce

❌ Don’t use ChaCha20-Poly1305 for:

  1. Random nonces - use XChaCha20-Poly1305 or XAES-256-GCM

ChaCha20-Poly1305 vs AES-GCM

Choose ChaCha20-Poly1305 when:

  • No hardware AES acceleration is available
  • Constant-time software implementation matters [2]

Choose AES-GCM when:

  • Standards compliance requires AES; GCM is a NIST recommendation [9]

Both require a nonce that never repeats under a key [2][9].

Exceptions

  • HashVerificationFilter::HashVerificationFailed - Authentication failed in AuthenticatedDecryptionFilter (wrong key, corrupted data, or modified ciphertext/AAD) [5]
  • InvalidKeyLength - Key is not 32 bytes [10]
  • InvalidArgument - Nonce is not 12 bytes [10]

See Also

References

  1. cryptopp-modern History.txt at 2026.11.0, release 8.1.0: “add IETF ChaCha, XChaCha, ChaChaPoly1305 and XChaChaPoly1305”.
  2. RFC 8439: ChaCha20 and Poly1305 for IETF Protocols, sections 1, 2.6, 2.8 and 4.
  3. chachapoly.h at 2026.11.0, file description.
  4. chachapoly.h at 2026.11.0, key, IV, tag and length limits, and the one-shot functions.
  5. filters.cpp at 2026.11.0, AuthenticatedDecryptionFilter forwards decrypted data before the final tag check.
  6. draft-irtf-cfrg-xchacha-03: XChaCha: eXtended-nonce ChaCha and AEAD_XChaCha20_Poly1305, section 2.1.
  7. WireGuard: Protocol and Cryptography, AEAD function definition.
  8. RFC 8446: The Transport Layer Security (TLS) Protocol Version 1.3, appendix B.4.
  9. NIST SP 800-38D: Galois/Counter Mode (GCM) and GMAC, sections 3 and 8.
  10. cryptlib.cpp at 2026.11.0, key and IV length checks.