XChaCha20-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
XChaCha20-Poly1305 is an authenticated encryption with associated data (AEAD) cipher that extends ChaCha20-Poly1305 with a 192-bit (24-byte) nonce instead of a 96-bit (12-byte) one. HChaCha20 derives a subkey from the key and the first 16 bytes of the nonce, and that subkey is used with ChaCha20-Poly1305. The specification is an IRTF CFRG Internet-Draft with Informational intended status, not an RFC [2].
The larger nonce is what makes random nonces practical: the draft states that random nonces allow 2^80 messages under one key with a 2^-32 chance of a collision [2].
Quick Example
#include <cryptopp/chachapoly.h>
#include <cryptopp/osrng.h>
#include <cryptopp/filters.h>
#include <cryptopp/secblock.h>
#include <iostream>
int main() {
using namespace CryptoPP;
AutoSeededRandomPool rng;
// 256-bit key
SecByteBlock key(32);
rng.GenerateBlock(key, key.size());
// 192-bit (24-byte) nonce - can be random!
byte nonce[24];
rng.GenerateBlock(nonce, sizeof(nonce));
std::string plaintext = "Hello, World!";
std::string ciphertext, recovered;
// Encrypt
XChaCha20Poly1305::Encryption enc;
enc.SetKeyWithIV(key, key.size(), nonce, sizeof(nonce));
StringSource(plaintext, true,
new AuthenticatedEncryptionFilter(enc,
new StringSink(ciphertext)
)
);
// Decrypt
XChaCha20Poly1305::Decryption dec;
dec.SetKeyWithIV(key, key.size(), nonce, sizeof(nonce));
StringSource(ciphertext, true,
new AuthenticatedDecryptionFilter(dec,
new StringSink(recovered)
)
);
std::cout << "Decrypted: " << recovered << std::endl;
return 0;
}Usage Guidelines
Do:
- Generate a random 24-byte nonce for each message [2]
- Use when random nonce generation is simpler than tracking counters
- Store the nonce alongside the ciphertext (it is not secret)
Avoid:
- Truncating or reusing nonces
- Using the plaintext before the tag has been verified
Where a protocol already maintains a message counter, we recommend ChaCha20-Poly1305, which is the RFC-specified construction and is a TLS 1.3 cipher suite [3][4].
Why XChaCha20-Poly1305?
The key advantage over standard ChaCha20-Poly1305:
| Property | ChaCha20-Poly1305 | XChaCha20-Poly1305 |
|---|---|---|
| Nonce size | 12 bytes (96-bit) | 24 bytes (192-bit) |
| Random nonces | ❌ Must not be random [3] | ✅ 2^80 messages at 2^-32 collision risk [2] |
| Counter tracking | Required | Optional |
| Use case | TLS, protocols with counters | Stored data, stateless senders |
Collision figures for random 24-byte nonces [2]:
- About 2^96 messages for a 50% chance of a single collision
- 2^80 messages for a 2^-32 chance of a collision
Class: XChaCha20Poly1305
Constants
// Key size: 32 bytes (256 bits)
// Nonce size: 24 bytes (192 bits)
// Tag size: 16 bytes (128 bits)
The library accepts only a 32-byte key and only a 24-byte nonce, and its full tag is 16 bytes [5].
Types
XChaCha20Poly1305::Encryption // For encryption
XChaCha20Poly1305::Decryption // For decryption
Methods
SetKeyWithIV()
void SetKeyWithIV(const byte* key, size_t keyLen,
const byte* iv, size_t ivLen);Set key and nonce (IV).
Parameters:
key- 32-byte keykeyLen- Key length (must be 32)iv- 24-byte nonceivLen- Nonce length (must be 24)
Example:
XChaCha20Poly1305::Encryption enc;
enc.SetKeyWithIV(key, 32, nonce, 24);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);Encrypt and authenticate in one call.
Parameters:
ciphertext- Output buffer (same size as message)mac- Output buffer for authentication tagmacSize- Tag size. Use 16. XChaCha20-Poly1305 builds on the RFC 8439 AEAD, which requires the complete tag: “Tag truncation MUST NOT be done” [2][3]. The library accepts smaller values [5], but a truncated tag is not the specified constructioniv- 24-byte nonceivLength- Nonce lengthaad- Additional authenticated data (optional)aadLength- AAD lengthmessage- PlaintextmessageLength- Plaintext length
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);Decrypt and verify in one call.
Returns: true if tag verification succeeds, false otherwise [5]
Complete Example: File Encryption with Random Nonce
The decryption side decrypts into memory and writes the file only after the tag has verified, because AuthenticatedDecryptionFilter forwards decrypted data to its attachment before the final tag check [6].
#include <cryptopp/chachapoly.h>
#include <cryptopp/osrng.h>
#include <cryptopp/files.h>
#include <cryptopp/filters.h>
#include <cryptopp/secblock.h>
#include <cstring>
#include <iostream>
#include <stdexcept>
using namespace CryptoPP;
void encryptFile(const std::string& inputFile,
const std::string& outputFile,
const SecByteBlock& key) {
AutoSeededRandomPool rng;
// Generate random 24-byte nonce (safe with XChaCha20!)
byte nonce[24];
rng.GenerateBlock(nonce, sizeof(nonce));
// Read plaintext
std::string plaintext;
FileSource(inputFile.c_str(), true,
new StringSink(plaintext)
);
// Encrypt
XChaCha20Poly1305::Encryption enc;
enc.SetKeyWithIV(key, key.size(), nonce, sizeof(nonce));
std::string ciphertext;
StringSource(plaintext, true,
new AuthenticatedEncryptionFilter(enc,
new StringSink(ciphertext)
)
);
// Write: nonce || ciphertext || tag
FileSink output(outputFile.c_str());
output.Put(nonce, sizeof(nonce));
output.Put((const byte*)ciphertext.data(), ciphertext.size());
std::cout << "Encrypted: " << inputFile << " -> " << outputFile << std::endl;
std::cout << "Nonce: " << sizeof(nonce) << " bytes (random, stored in file)" << std::endl;
}
void decryptFile(const std::string& inputFile,
const std::string& outputFile,
const SecByteBlock& key) {
// Read encrypted file
std::string encrypted;
FileSource(inputFile.c_str(), true,
new StringSink(encrypted)
);
// Extract nonce (first 24 bytes)
if (encrypted.size() < 24) {
throw std::runtime_error("File too small");
}
byte nonce[24];
std::memcpy(nonce, encrypted.data(), sizeof(nonce));
std::string ciphertext = encrypted.substr(24);
// Decrypt into memory; throws HashVerificationFailed on a bad tag
XChaCha20Poly1305::Decryption dec;
dec.SetKeyWithIV(key, key.size(), nonce, sizeof(nonce));
std::string plaintext;
StringSource(ciphertext, true,
new AuthenticatedDecryptionFilter(dec,
new StringSink(plaintext)
)
);
// Tag verified: write plaintext
FileSink output(outputFile.c_str());
output.Put((const byte*)plaintext.data(), plaintext.size());
std::cout << "Decrypted: " << inputFile << " -> " << outputFile << std::endl;
}
int main() {
AutoSeededRandomPool rng;
// Generate key (store securely in practice!)
SecByteBlock key(32);
rng.GenerateBlock(key, key.size());
encryptFile("document.txt", "document.enc", key);
decryptFile("document.enc", "document.dec.txt", key);
return 0;
}Complete Example: Message Encryption with AAD
#include <cryptopp/chachapoly.h>
#include <cryptopp/osrng.h>
#include <cryptopp/filters.h>
#include <cryptopp/secblock.h>
#include <iostream>
using namespace CryptoPP;
struct EncryptedMessage {
byte nonce[24];
std::string ciphertext; // Includes 16-byte tag
};
EncryptedMessage encryptWithAAD(const std::string& plaintext,
const std::string& aad,
const SecByteBlock& key) {
AutoSeededRandomPool rng;
EncryptedMessage msg;
// Random nonce (safe with 24 bytes!)
rng.GenerateBlock(msg.nonce, sizeof(msg.nonce));
XChaCha20Poly1305::Encryption enc;
enc.SetKeyWithIV(key, key.size(), msg.nonce, sizeof(msg.nonce));
// Create filter with AAD
AuthenticatedEncryptionFilter ef(enc,
new StringSink(msg.ciphertext)
);
// Process AAD first (authenticated but not encrypted)
ef.ChannelPut(AAD_CHANNEL,
(const byte*)aad.data(), aad.size());
ef.ChannelMessageEnd(AAD_CHANNEL);
// Process plaintext (encrypted and authenticated)
ef.ChannelPut(DEFAULT_CHANNEL,
(const byte*)plaintext.data(), plaintext.size());
ef.ChannelMessageEnd(DEFAULT_CHANNEL);
return msg;
}
std::string decryptWithAAD(const EncryptedMessage& msg,
const std::string& aad,
const SecByteBlock& key) {
XChaCha20Poly1305::Decryption dec;
dec.SetKeyWithIV(key, key.size(), msg.nonce, sizeof(msg.nonce));
std::string plaintext;
AuthenticatedDecryptionFilter df(dec,
new StringSink(plaintext)
);
// Process AAD
df.ChannelPut(AAD_CHANNEL,
(const byte*)aad.data(), aad.size());
df.ChannelMessageEnd(AAD_CHANNEL);
// Process ciphertext
df.ChannelPut(DEFAULT_CHANNEL,
(const byte*)msg.ciphertext.data(), msg.ciphertext.size());
df.ChannelMessageEnd(DEFAULT_CHANNEL);
return plaintext;
}
int main() {
AutoSeededRandomPool rng;
SecByteBlock key(32);
rng.GenerateBlock(key, key.size());
std::string message = "Secret payment data";
std::string header = "Transaction-ID: 12345"; // AAD
// Encrypt with AAD
EncryptedMessage encrypted = encryptWithAAD(message, header, key);
std::cout << "Ciphertext size: " << encrypted.ciphertext.size()
<< " bytes (includes 16-byte tag)" << std::endl;
// Decrypt with same AAD
std::string decrypted = decryptWithAAD(encrypted, header, key);
std::cout << "Decrypted: " << decrypted << std::endl;
// Tampered AAD will fail
try {
decryptWithAAD(encrypted, "Tampered-Header", key);
} catch (const Exception& e) {
std::cout << "Tampered AAD detected!" << std::endl;
}
return 0;
}Performance
Compared with ChaCha20-Poly1305, each message adds one HChaCha20 computation to derive the subkey [2].
XChaCha20-Poly1305 vs ChaCha20-Poly1305
| Property | ChaCha20-Poly1305 | XChaCha20-Poly1305 |
|---|---|---|
| Nonce | 12 bytes | 24 bytes [2] |
| Random nonce | ❌ Must not be random [3] | ✅ Intended use [2] |
| Specification | RFC 8439 [3] | IRTF Internet-Draft [2] |
| TLS 1.3 | ✅ Cipher suite [4] | ❌ Not a TLS 1.3 cipher suite [4] |
| File encryption | ⚠️ Needs a counter | ✅ Random OK |
Security
Security Properties
- Key size: 256 bits [5]
- Nonce size: 192 bits (24 bytes) [2][5]
- Tag size: 128 bits (16 bytes) [5]
- Max message per nonce: 274,877,906,880 bytes (nearly 256 GB) [5]
- Random nonces: 2^80 messages per key at a 2^-32 collision probability [2]
- Security argument: the draft states that as long as ChaCha20-Poly1305 is a secure AEAD and ChaCha is a secure PRF, XChaCha20-Poly1305 is secure [2]
When Random Nonces Are Safe
XChaCha20-Poly1305 with 24-byte random nonce:
- Nonce space: 2^192
- About 2^96 messages for a 50% chance of a collision
- 2^80 messages for a 2^-32 chance of a collision
ChaCha20-Poly1305 with 12-byte nonce:
- RFC 8439: the nonce must not be randomly generated; use a counterSecurity Notes
- Nonce uniqueness: random nonces are safe within the limits above, but never reuse a (key, nonce) pair
- No nonce misuse resistance: a repeated nonce gives the same subkey and the same ChaCha20-Poly1305 nonce [2], so it reveals the XOR of the plaintexts as in ChaCha20-Poly1305 [3]
- AAD integrity: AAD is authenticated but not encrypted
- Message volume: stay within 2^80 random-nonce messages per key for a 2^-32 collision probability [2]
XChaCha20-Poly1305 vs AES-GCM
| Property | XChaCha20-Poly1305 | AES-GCM |
|---|---|---|
| Nonce size | 24 bytes [2] | 12 bytes recommended [7] |
| Random nonce | ✅ 2^80 messages at 2^-32 [2] | ⚠️ At most 2^32 messages per key [7] |
| Nonce reuse | Catastrophic | Catastrophic [7] |
Use XChaCha20-Poly1305 when:
- Random nonce generation is preferred
- No AES hardware is available; RFC 8439 gives ChaCha20 the speed advantage there [3]
- Encrypting many messages with the same key
Use AES-GCM when:
- The protocol manages nonces, as TLS does
- A NIST-specified mode is required [7]
When to Use XChaCha20-Poly1305
✅ Use XChaCha20-Poly1305 for:
- File Encryption - Random nonces avoid stored counter state
- Database Encryption - Each record gets a random nonce
- Long-lived Keys - 2^80 random-nonce messages at a 2^-32 collision probability [2]
- Backup Encryption - No counter state to manage
- Stateless Encryption - No need to track nonce counters
❌ Don’t use XChaCha20-Poly1305 for:
- TLS/HTTPS - TLS 1.3 uses ChaCha20-Poly1305 [4]
Exceptions
InvalidKeyLength- Key not 32 bytes [8]InvalidArgument- Nonce not 24 bytes [8]HashVerificationFilter::HashVerificationFailed- Tag verification failed inAuthenticatedDecryptionFilter[6]
See Also
- ChaCha20-Poly1305 - Standard 12-byte nonce variant
- XAES-256-GCM - AES-based extended-nonce AEAD
- AES-GCM - Hardware-accelerated AEAD
- HKDF - Key derivation
- AutoSeededRandomPool - Random nonce generation
References
- cryptopp-modern History.txt at 2026.11.0, release 8.1.0: “add IETF ChaCha, XChaCha, ChaChaPoly1305 and XChaChaPoly1305”.
- draft-irtf-cfrg-xchacha-03: XChaCha: eXtended-nonce ChaCha and AEAD_XChaCha20_Poly1305, status, sections 2, 2.1 and 2.2.
- RFC 8439: ChaCha20 and Poly1305 for IETF Protocols, sections 1, 2.6 and 4.
- RFC 8446: The Transport Layer Security (TLS) Protocol Version 1.3, appendix B.4.
- chachapoly.h at 2026.11.0, XChaCha20Poly1305 key, IV, tag and length limits, and the one-shot functions.
- filters.cpp at 2026.11.0,
AuthenticatedDecryptionFilterforwards decrypted data before the final tag check. - NIST SP 800-38D: Galois/Counter Mode (GCM) and GMAC, sections 5.2.1.1, 8 and 8.3.
- cryptlib.cpp at 2026.11.0, key and IV length checks.