Poly1305
Header: #include <cryptopp/poly1305.h> | Namespace: CryptoPP
Since: Crypto++ 6.0; Poly1305TLS and ChaCha20Poly1305 since Crypto++ 8.1
Thread Safety: Not thread-safe per instance; use separate instances per thread
Poly1305 is a one-time authenticator designed by Daniel J. Bernstein. It takes a 32-byte one-time key and a message and produces a 16-byte tag, and it is the authenticator in the ChaCha20-Poly1305 AEAD of RFC 8439. RFC 8439 prohibits using the same Poly1305 key twice.
ChaCha20Poly1305, which derives the one-time Poly1305 key from the ChaCha20 key and nonce. Poly1305TLS is the IETF Poly1305 of RFC 8439, and Poly1305<AES> is Bernstein’s original Poly1305-AES.Quick Example (ChaCha20-Poly1305 - Recommended)
#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;
// Long-term key (32 bytes)
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);
std::string message = "Message to authenticate and encrypt";
std::string ciphertext;
// Encrypt and authenticate in one operation
ChaCha20Poly1305::Encryption enc;
enc.SetKeyWithIV(key, key.size(), nonce, sizeof(nonce));
StringSource(message, true,
new AuthenticatedEncryptionFilter(enc,
new StringSink(ciphertext)
)
);
// ciphertext includes the 16-byte Poly1305 tag
std::cout << "Ciphertext + tag: " << ciphertext.size() << " bytes" << std::endl;
return 0;
}RFC 8439 says the nonce must be unique per key and must not be randomly generated; a counter is a good way to do this. For random nonces use XChaCha20-Poly1305.
Usage Guidelines
- Use ChaCha20-Poly1305 for combined encryption + authentication
- For raw
Poly1305TLS, use a fresh, unpredictable one-time key per message - For raw
Poly1305<AES>, never reuse a nonce under a key - For ChaCha20-Poly1305, use a counter nonce that never repeats under a key (the library derives the one-time Poly1305 key internally)
- CRITICAL: Never reuse a Poly1305 key for multiple messages
- Random 12-byte nonces with ChaCha20-Poly1305
- Don’t use standalone Poly1305 without understanding one-time semantics
- Don’t use for password hashing (use Argon2)
- Prefer ChaCha20-Poly1305 AEAD over standalone Poly1305
Why One-Time?
RFC 8439 defines Poly1305 with a one-time key: the (r, s) pair must be unique and unpredictable for each invocation, and the same key must not be used twice. Bernstein’s Poly1305-AES likewise requires that the sender never use the same nonce for two different messages. The library does not enforce this. Poly1305<AES> has a debug-only assertion that fires when a second tag is computed without an intervening Resynchronize(); it does not remember nonce values, so supplying the same nonce again through Resynchronize() clears the flag and the assertion passes.
Solution: Use ChaCha20-Poly1305, which derives a fresh Poly1305 key for each nonce:
// CORRECT - ChaCha20-Poly1305 handles key derivation
ChaCha20Poly1305::Encryption enc;
enc.SetKeyWithIV(key, 32, nonce, 12); // Unique counter nonce per message
// The Poly1305 key is derived from (key, nonce): reuse the key, never the nonce
Crypto++ Poly1305 Classes
Crypto++ provides several Poly1305 implementations:
| Class | Use Case |
|---|---|
ChaCha20Poly1305 | Recommended - Combined AEAD cipher (RFC 8439) |
XChaCha20Poly1305 | Extended nonce variant (192-bit nonce) |
Poly1305TLS | IETF Poly1305 from RFC 8439; 32-byte one-time key |
Poly1305<AES> | Bernstein’s Poly1305-AES; 32-byte key and 16-byte nonce |
ChaCha20Poly1305 Constants
ChaCha20Poly1305 has no DEFAULT_KEYLENGTH or IV_LENGTH constants; the sizes come from member functions:
Key size: 32 bytes (MinKeyLength(), MaxKeyLength(), DefaultKeyLength())
IV size: 12 bytes (IVSize(); XChaCha20Poly1305: 24 bytes)
Tag size: 16 bytes (DigestSize())Complete Examples
Example 1: ChaCha20-Poly1305 Encryption & Authentication
#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;
// Long-term key (can be reused with different nonces)
SecByteBlock key(32);
rng.GenerateBlock(key, key.size());
// Unique counter nonce per message
word64 messageNumber = 1;
byte nonce[12] = {0};
PutWord(false, BIG_ENDIAN_ORDER, nonce + 4, messageNumber);
std::string plaintext = "Secret message";
std::string ciphertext, recovered;
// Encrypt and authenticate
ChaCha20Poly1305::Encryption enc;
enc.SetKeyWithIV(key, key.size(), nonce, sizeof(nonce));
StringSource(plaintext, true,
new AuthenticatedEncryptionFilter(enc,
new StringSink(ciphertext)
)
);
// Decrypt and verify
ChaCha20Poly1305::Decryption dec;
dec.SetKeyWithIV(key, key.size(), nonce, sizeof(nonce));
try {
StringSource(ciphertext, true,
new AuthenticatedDecryptionFilter(dec,
new StringSink(recovered)
)
);
std::cout << "Decrypted: " << recovered << std::endl;
} catch (const HashVerificationFilter::HashVerificationFailed&) {
recovered.clear(); // may hold unauthenticated data; discard it
std::cerr << "Authentication failed!" << std::endl;
return 1;
}
return 0;
}AuthenticatedDecryptionFilter throws HashVerificationFailed by default when the tag does not match. It passes decrypted data downstream before the final tag check, so discard the output on failure.
Example 2: XChaCha20-Poly1305 (Extended Nonce)
#include <cryptopp/chachapoly.h>
#include <cryptopp/osrng.h>
#include <cryptopp/filters.h>
int main() {
using namespace CryptoPP;
AutoSeededRandomPool rng;
// 32-byte key
SecByteBlock key(32);
rng.GenerateBlock(key, key.size());
// 24-byte nonce (extended), long enough to generate at random
byte nonce[24];
rng.GenerateBlock(nonce, sizeof(nonce));
std::string plaintext = "Message with extended nonce";
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 (throws HashVerificationFailed if the tag does not match)
XChaCha20Poly1305::Decryption dec;
dec.SetKeyWithIV(key, key.size(), nonce, sizeof(nonce));
StringSource(ciphertext, true,
new AuthenticatedDecryptionFilter(dec,
new StringSink(recovered)
)
);
return 0;
}The XChaCha draft says random 192-bit nonces allow 2^80 messages under one key at a 2^-32 chance of a collision.
For file encryption with a random nonce, see the complete example on the XChaCha20-Poly1305 page.
Performance
Bernstein describes Poly1305-AES as computable at extremely high speed, and as parallelizable and incremental. Poly1305<AES>::AlgorithmProvider() reports the AES implementation it uses.
Security Properties
| Property | Value |
|---|---|
| Tag size | 128 bits (16 bytes) |
| Forgery bound (RFC 8439) | Forgeries rejected with probability 1-(n/2^102) for a 16n-byte message, even after 2^64 legitimate messages |
| Forgery bound (Poly1305-AES) | Within 14D*ceil(L/16)/2^106 of AES’s security, for messages of at most L bytes, at most 2^64 authenticated messages and D forgery attempts |
| Key type | One-time key per message (Poly1305TLS, ChaCha20-Poly1305); unique nonce per message (Poly1305<AES>) |
Key Reuse
RFC 8439 prohibits using the same Poly1305 key twice and requires the key to be unpredictable. The Poly1305-AES security guarantee assumes the sender never uses the same nonce for two messages. Neither Crypto++ class enforces this.
Poly1305 vs Other MACs
| Feature | Poly1305 | HMAC-SHA256 | AES-CMAC |
|---|---|---|---|
| Key reuse | No: one-time key | Yes | Yes, within 2^48 messages |
| Output size | 16 bytes | 32 bytes | 16 bytes |
| Security | Forgery about n/2^102 for a 16n-byte message | Up to 256-bit strength | 1 in 2^128 tag guess; 2^48 messages per key |
| Common use | With ChaCha20 | General | With AES |
When to Use Poly1305
Use Poly1305 for:
- ChaCha20-Poly1305 AEAD - Combined encryption + authentication
- TLS 1.3 - The
TLS_CHACHA20_POLY1305_SHA256cipher suite - WireGuard - Its AEAD is ChaCha20Poly1305
Don’t use standalone Poly1305 for:
- Multiple messages with same key - Use HMAC instead
- Password authentication - Use Argon2
- When you need simplicity - HMAC needs no per-message key or nonce
Integration with ChaCha20
The recommended way to use Poly1305:
#include <cryptopp/chachapoly.h>
#include <cryptopp/osrng.h>
#include <cryptopp/filters.h>
#include <cryptopp/misc.h>
#include <cstring>
#include <limits>
#include <stdexcept>
#include <string>
using namespace CryptoPP;
class MessageCipher {
SecByteBlock key;
word64 counter;
public:
MessageCipher() : key(32), counter(0) {
AutoSeededRandomPool rng;
rng.GenerateBlock(key, key.size());
}
// A copy would carry the same key and counter and so repeat nonces: forbid copying
MessageCipher(const MessageCipher&) = delete;
MessageCipher& operator=(const MessageCipher&) = delete;
std::string encrypt(const std::string& plaintext) {
// Construct nonce from counter; it must never repeat under this key.
// Refuse rather than wrap: a wrapped counter would reuse nonce 0.
if (counter == std::numeric_limits<word64>::max())
throw std::runtime_error("nonce counter exhausted; rekey");
byte nonce[12] = {0};
PutWord(false, BIG_ENDIAN_ORDER, nonce + 4, counter);
counter++;
ChaCha20Poly1305::Encryption enc;
enc.SetKeyWithIV(key, key.size(), nonce, sizeof(nonce));
std::string ciphertext;
// Prepend nonce to ciphertext
ciphertext.assign(reinterpret_cast<const char*>(nonce), sizeof(nonce));
std::string encrypted;
StringSource(plaintext, true,
new AuthenticatedEncryptionFilter(enc,
new StringSink(encrypted)
)
);
ciphertext += encrypted;
return ciphertext;
}
std::string decrypt(const std::string& ciphertext) {
if (ciphertext.size() < 12 + 16) {
throw std::runtime_error("Ciphertext too short");
}
// Extract nonce
byte nonce[12];
std::memcpy(nonce, ciphertext.data(), 12);
ChaCha20Poly1305::Decryption dec;
dec.SetKeyWithIV(key, key.size(), nonce, sizeof(nonce));
// Throws HashVerificationFailed if the tag does not match
std::string plaintext;
StringSource(ciphertext.substr(12), true,
new AuthenticatedDecryptionFilter(dec,
new StringSink(plaintext)
)
);
return plaintext;
}
};Error Handling
#include <cryptopp/chachapoly.h>
#include <cryptopp/filters.h>
#include <iostream>
using namespace CryptoPP;
void safeDecrypt(const std::string& ciphertext,
const SecByteBlock& key,
const byte* nonce) {
try {
ChaCha20Poly1305::Decryption dec;
dec.SetKeyWithIV(key, key.size(), nonce, 12);
std::string plaintext;
StringSource(ciphertext, true,
new AuthenticatedDecryptionFilter(dec,
new StringSink(plaintext)
)
);
std::cout << "Decryption successful" << std::endl;
} catch (const HashVerificationFilter::HashVerificationFailed&) {
std::cerr << "AUTHENTICATION FAILED - data tampered!" << std::endl;
// Don't use the data!
} catch (const Exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
}Thread Safety
ChaCha20Poly1305 objects are not thread-safe:
// WRONG - shared across threads
ChaCha20Poly1305::Encryption sharedEnc;
// CORRECT - per-thread instances; each thread needs nonces that never
// collide with another thread's under the same key (for example, a
// per-thread prefix in the nonce)
void encryptInThread(const std::string& plaintext,
const SecByteBlock& key,
const byte nonce[12]) {
ChaCha20Poly1305::Encryption enc;
enc.SetKeyWithIV(key, key.size(), nonce, 12);
std::string ciphertext;
StringSource(plaintext, true,
new AuthenticatedEncryptionFilter(enc,
new StringSink(ciphertext)
)
);
}See Also
- ChaCha20-Poly1305 - Recommended AEAD
- HMAC - Reusable key MAC
- CMAC - Block cipher MAC
- AES-GCM - Alternative AEAD
- Security Concepts - Nonce management
References
- RFC 8439: ChaCha20 and Poly1305 for IETF Protocols
- Bernstein: The Poly1305-AES message-authentication code (2005)
- draft-irtf-cfrg-xchacha-03: XChaCha: eXtended-nonce ChaCha and AEAD_XChaCha20_Poly1305
- NIST SP 800-57 Part 1 Revision 5: Recommendation for Key Management
- RFC 8446: The Transport Layer Security (TLS) Protocol Version 1.3
- WireGuard: Protocol and Cryptography