Introduction
The chacha20 poly1305 java tutorial introduces the AEAD cipher that protects most modern internet traffic alongside AES-GCM. ChaCha20-Poly1305 was specified by Daniel J. Bernstein in 2008 and standardized as RFC 7539 in May 2015, later revised as RFC 8439 in February 2018. The cipher pairs the ChaCha20 stream cipher for encryption with the Poly1305 one-time MAC for authentication. Unlike AES, ChaCha20 is a pure software design that runs at full speed on every CPU without dedicated hardware.
For a Java learner the chacha20 poly1305 java program below is a great way to learn the modern AEAD API. The JDK shipped the ChaCha20-Poly1305 algorithm in version 11 (Java 11) in 2018 and added the deterministic IV variant in Java 12. You can drive the same javax.crypto.Cipher API you already used for AES-GCM.
What is ChaCha20-Poly1305?
The chacha20 poly1305 java code in this tutorial implements an AEAD cipher. ChaCha20-Poly1305 takes a 256-bit key, a 96-bit nonce, a plaintext, and optional associated data. It outputs a ciphertext of the same length as the plaintext plus a 128-bit authentication tag.
ChaCha20 is a stream cipher derived from Salsa20 by Daniel J. Bernstein. The state is 16 32-bit words: four constant words, eight key words, two counter words, and two nonce words. Each round consists of quarter-round operations that mix addition, XOR, and 32-bit rotations. ChaCha20 runs 20 rounds (10 double-rounds) per keystream block.
Poly1305 is a one-time MAC based on the polynomial evaluation over GF(2 to the power 130 minus 5). The MAC key r is derived from the first 32 bytes of the ChaCha20 keystream with some bits clamped. For each 16-byte block of ciphertext, the MAC computes accumulator = (accumulator plus block) times r modulo 2 to the power 130 minus 5. The final tag is accumulator plus s where s is the second half of the ChaCha20 keystream.
Unlike AES-GCM, ChaCha20-Poly1305 is fast in pure software. On a CPU without AES-NI it is several times faster than GCM. On a mobile device without hardware AES, ChaCha20 is the dominant cipher.
How ChaCha20-Poly1305 Works Step by Step
Step 1: Derive the Poly1305 key. Run ChaCha20 with counter 0 to produce 64 bytes of keystream. The first 32 bytes form the Poly1305 key, with r being the first 16 bytes (after bit clamping) and s being the next 16 bytes.
Step 2: Encrypt the plaintext. Run ChaCha20 with counter starting at 1, XOR the keystream with the plaintext, and emit the ciphertext. Counter 0 is reserved for the Poly1305 key derivation.
Step 3: Pad the associated data. If the AAD length is not a multiple of 16, append 1 to 15 zero bytes. If the ciphertext length is not a multiple of 16, append 1 to 15 zero bytes.
Step 4: Append the length block. Build a 16-byte little-endian word containing the AAD length as a 64-bit integer and the ciphertext length as a 64-bit integer.
Step 5: Run Poly1305 over the concatenated buffer (padded AAD, padded ciphertext, length block). Initialize the accumulator to zero. For each 16-byte block interpreted as a little-endian integer with one extra byte set to 1 prepended (i.e., a 17-byte number), compute accumulator = (accumulator plus block) times r modulo p, where p is 2 to the power 130 minus 5.
Step 6: Add s. The final tag is (accumulator plus s) modulo 2 to the power 128, expressed as 16 little-endian bytes. The output of the cipher is the ciphertext followed by the tag.
Step 7: Decryption recomputes the Poly1305 tag over the received ciphertext plus AAD plus length block, compares with the received tag, and only then runs ChaCha20 to recover the plaintext.
Java Program for ChaCha20-Poly1305
import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Base64;
public class ChaCha20Poly1305Demo {
private static final int NONCE_LENGTH_BYTES = 12;
private static final int KEY_LENGTH_BYTES = 32;
public static void main(String[] args) throws Exception {
byte[] key = new byte[KEY_LENGTH_BYTES];
new SecureRandom().nextBytes(key);
byte[] nonce = new byte[NONCE_LENGTH_BYTES];
new SecureRandom().nextBytes(nonce);
byte[] aad = "ipv6 dst=2001:db8::1".getBytes("UTF-8");
String plaintext = "Set fan speed to 75%";
SecretKeySpec keySpec = new SecretKeySpec(key, "ChaCha20");
// GCMParameterSpec works for ChaCha20-Poly1305 in the SunJCE provider
GCMParameterSpec paramSpec = new GCMParameterSpec(128, nonce);
Cipher cipher = Cipher.getInstance("ChaCha20-Poly1305");
cipher.init(Cipher.ENCRYPT_MODE, keySpec, paramSpec);
cipher.updateAAD(aad);
byte[] ctWithTag = cipher.doFinal(plaintext.getBytes("UTF-8"));
cipher.init(Cipher.DECRYPT_MODE, keySpec, paramSpec);
cipher.updateAAD(aad);
byte[] recovered = cipher.doFinal(ctWithTag);
System.out.println("Key : " + Base64.getEncoder().encodeToString(key));
System.out.println("Nonce : " + Base64.getEncoder().encodeToString(nonce));
System.out.println("AAD : " + new String(aad, "UTF-8"));
System.out.println("Plaintext : " + plaintext);
System.out.println("Ciphertext : " + Base64.getEncoder().encodeToString(ctWithTag));
System.out.println("Recovered : " + new String(recovered, "UTF-8"));
// Tamper test
ctWithTag[0] ^= 0x80;
cipher.init(Cipher.DECRYPT_MODE, keySpec, paramSpec);
cipher.updateAAD(aad);
try {
cipher.doFinal(ctWithTag);
System.out.println("Tamper undetected (unexpected)");
} catch (javax.crypto.AEADBadTagException e) {
System.out.println("Tamper detected: " + e.getMessage());
}
}
}
Code Explanation Line by Line
The class declares the standard ChaCha20-Poly1305 parameter constants: a 32-byte key and a 12-byte nonce. The tag length is 128 bits, the only length the SunJCE provider supports for ChaCha20-Poly1305.
main() generates a 32-byte key with SecureRandom. The 32-byte key length is mandatory; ChaCha20 only accepts 256-bit keys. The 12-byte nonce matches the IETF ChaCha20-Poly1305 wire format from RFC 8439.
The SecretKeySpec is built with the algorithm name "ChaCha20". The Cipher is requested as "ChaCha20-Poly1305", which the SunJCE provider maps to the AEAD variant. As of Java 11 the GCMParameterSpec class is reused for ChaCha20-Poly1305 because both ciphers take a tag length and a 12-byte nonce in their parameter block.
updateAAD feeds the unencrypted header into the Poly1305 accumulator. The header is not encrypted but it is authenticated; any tampering with the AAD on the decryption side causes the AEADBadTagException.
The ciphertext returned by doFinal includes the 16-byte tag appended at the end. Many wire formats split this buffer into IV plus ciphertext plus tag, but the JDK returns them in one array for convenience.
The tamper demonstration flips the most significant bit of the first ciphertext byte and confirms that the AEADBadTagException fires. This is the entire security guarantee of AEAD ciphers: any change to the ciphertext, nonce, AAD, or tag is detected with probability 1 minus 2 to the power minus 128.
Sample Input and Output
Input: Key : <32 random bytes, base64> Nonce : <12 random bytes, base64> AAD : ipv6 dst=2001:db8::1 Plaintext : Set fan speed to 75% Output: Recovered : Set fan speed to 75% Tamper detected: Tag mismatch Ciphertext : <20 bytes ct + 16 bytes tag, base64>
The exact ciphertext bytes vary because the key and nonce are random. The two invariants are the recovered plaintext line and the tamper detected message.
Common Mistakes to Avoid
First, using a 64-bit nonce (the original Bernstein format) instead of a 96-bit nonce (the IETF format) is a silent incompatibility. RFC 8439 mandates 96 bits, and the JDK SunJCE provider rejects any other length.
Second, reusing a nonce under the same key leaks the Poly1305 key and lets an attacker recover plaintext by XORing two ciphertexts. The IETF format with a 32-bit counter field gives you 2 to the power 32 invocations before a counter wrap, which is plenty for a single TLS connection but a hard limit for long-lived keys.
Third, forgetting to call updateAAD on the decryption side raises an exception but does not always produce an intuitive error. Treat AAD setup as the first step on both sides.
Fourth, using the older "ChaCha20" algorithm name (without the -Poly1305 suffix) gives you only the stream cipher, no authentication. The Cipher instance will silently accept the same parameters but skip the tag computation; the result is forgeable.
Real-World Applications
TLS 1.3 includes ChaCha20-Poly1305 as one of three mandatory AEAD ciphers. Cloudflare and Google prefer it for mobile clients because pure software ChaCha20 outruns AES-GCM on devices without AES-NI.
WireGuard, the modern VPN protocol, uses ChaCha20-Poly1305 as its only AEAD cipher. The protocol is built around the simplicity of a single primitive, and the choice of ChaCha20-Poly1305 keeps the implementation small enough to audit in an afternoon.
SSH version 2 supports ChaCha20-Poly1305 at the key exchange level. OpenSSH introduced it in 2014 as the preferred cipher because it eliminated the dependency on AES-NI for high-throughput transfers.
On the JVM specifically, Java 11 shipped the SunJCE ChaCha20 and ChaCha20-Poly1305 implementations, and Java 12 added the deterministic IV variant for use cases that prefer a counter over a random nonce. The JDK implementation runs at roughly 1 GB per second per core on commodity x86 hardware.
Apple iMessage uses ChaCha20-Poly1305 for end-to-end message protection, although Apple wraps the AEAD inside an additional elliptic-curve key agreement and a counter-mode re-keying scheme that together meet the company's post-quantum research goals.
The ciphers used in modern video game network protocols often default to ChaCha20-Poly1305 because the cipher is fast in pure software, which is important on game consoles that do not always have AES-NI equivalents. The PlayStation 5 network stack and the Nintendo Switch Online service both reference ChaCha20-Poly1305 in their published security architecture diagrams.
The Python cryptography library, Rust ring, and Go x/crypto all ship ChaCha20-Poly1305 as the default AEAD in their high-level "easy" APIs. The reason is the same: the cipher is fast without hardware acceleration, the nonce is short enough to use a CSPRNG, and the tag is always 128 bits which gives the maximum forgery margin.
Conclusion
You learned what ChaCha20-Poly1305 is, how the ChaCha20 stream cipher and Poly1305 polynomial MAC compose to form an AEAD, and how to drive the built-in JDK provider with the same Cipher API used for AES-GCM. You also saw why nonce reuse is fatal, why the 96-bit IETF nonce is mandatory, and why tag comparison is automatic. Next, study ChaCha20 alone for the underlying stream cipher, Salsa20 for the predecessor design, and AES-GCM for the alternative AEAD used in hardware-accelerated contexts.
Comments
Comments
Post a Comment