TExcelTAD
Home › Applied Cryptography: Ciphers, Hashes, Signatures, PKI & TLS › Authenticated Encryption: AES-GCM and ChaCha20-Poly1305

Authenticated Encryption: AES-GCM and ChaCha20-Poly1305

The last three lessons kept arriving at the same conclusion: encryption without integrity is dangerous. XOR ciphers are malleable, CBC is open to padding oracles, and a MAC added by hand is easy to get wrong (wrong order, wrong key, non-constant-time check). Authenticated encryption with associated data (AEAD) packages encryption and authentication into one primitive with one key and one call, and it is the default choice for any new design: TLS 1.3, QUIC, WireGuard and modern SSH ciphers (chacha20-poly1305@openssh.com, AES-GCM) all use it.

What an AEAD does

text
encrypt(key, nonce, plaintext, associated_data)  ->  ciphertext || tag
decrypt(key, nonce, ciphertext || tag, associated_data)  ->  plaintext   or   error
  • The ciphertext has the same length as the plaintext; the tag (16 bytes for both standard AEADs) authenticates the ciphertext and the associated data.
  • Associated data (AAD) is authenticated but not encrypted: headers, record numbers, a user id, a file format version. Anything that must not be changed or moved, but has to stay readable.
  • Decryption either returns the exact plaintext or fails. There is no partial result and no detail about why: a modified byte, a wrong key, a wrong nonce or wrong AAD all give the same error.

The two standard AEADs

AES-GCM ChaCha20-Poly1305
encryption AES in CTR mode ChaCha20 stream cipher
authenticator GHASH, a polynomial MAC over GF(2^128) Poly1305, a polynomial MAC mod 2^130 − 5
key / nonce / tag 16 or 32 bytes / 12 bytes / 16 bytes 32 bytes / 12 bytes / 16 bytes
specified in NIST SP 800-38D RFC 8439
fast where CPUs with AES and carry-less multiply instructions (most x86 and ARMv8 servers and phones) everywhere, in constant-time software; preferred on devices without AES hardware

Both are in every TLS 1.3 implementation (TLS_AES_128_GCM_SHA256, TLS_AES_256_GCM_SHA384, TLS_CHACHA20_POLY1305_SHA256).

Both, with tampering

The example encrypts an invoice with a JSON header as AAD, then tries three manipulations: changing the recipient in the header, flipping one ciphertext bit and cutting the tag. The key and nonce are fixed for stable output; real code uses AESGCM.generate_key(256) and os.urandom(12).

python · try it yourself
from cryptography.hazmat.primitives.ciphers.aead import AESGCM, ChaCha20Poly1305
from cryptography.exceptions import InvalidTag

key = bytes.fromhex("00" * 31 + "01")     # fixed for the lesson; real code: AESGCM.generate_key(256)
nonce = bytes.fromhex("000000000000000000000001")
header = b'{"v":1,"to":"bob"}'           # associated data: authenticated, not encrypted
body = b"invoice 2026-114: 1,250.00 EUR"

for Alg in (AESGCM, ChaCha20Poly1305):
    a = Alg(key)
    ct = a.encrypt(nonce, body, header)
    print(f"{Alg.__name__:17} {len(body)} -> {len(ct)} bytes, tag {ct[-16:].hex()[:16]}...")
    print("  decrypt:", a.decrypt(nonce, ct, header).decode())
    for what, args in [("changed header", (nonce, ct, b'{"v":1,"to":"eve"}')),
                       ("changed byte", (nonce, ct[:3] + bytes([ct[3] ^ 1]) + ct[4:], header)),
                       ("cut tag", (nonce, ct[:-1], header))]:
        try:
            a.decrypt(*args); print("  ", what, "ACCEPTED (bad)")
        except InvalidTag:
            print("  ", what, "-> InvalidTag")
AESGCM            30 -> 46 bytes, tag 2a0b639a2de84d36...
  decrypt: invoice 2026-114: 1,250.00 EUR
   changed header -> InvalidTag
   changed byte -> InvalidTag
   cut tag -> InvalidTag
ChaCha20Poly1305  30 -> 46 bytes, tag 272df1956a54de28...
  decrypt: invoice 2026-114: 1,250.00 EUR
   changed header -> InvalidTag
   changed byte -> InvalidTag
   cut tag -> InvalidTag

The 30-byte body became 46 bytes: 30 bytes of ciphertext and a 16-byte tag. Every manipulation fails the same way. The header {"v":1,"to":"bob"} was never encrypted, yet it can't be changed to eve without detection: that is what AAD is for. A typical use is binding a ciphertext to its context (the database row id, the user it belongs to) so an attacker can't copy a valid ciphertext from one row to another.

What an AEAD requires from you

  1. A unique nonce for every encryption under a key. This is the one rule, and breaking it is catastrophic: for GCM, two messages with the same nonce reveal the XOR of their plaintexts and let the attacker recover the GHASH key and forge tags (Nonce Reuse). The nonce is not secret; send it with the ciphertext.
  2. A limit on messages per key. With random 96-bit nonces, NIST SP 800-38D limits one key to 2^32 encryptions so the chance of a repeated nonce stays negligible. Counters avoid collisions completely but need state that survives restarts. XChaCha20-Poly1305 (libsodium, nacl.secret.SecretBox) has 192-bit nonces, which are safe to pick at random for any realistic volume.
  3. Never use plaintext before the tag is checked. Library one-shot APIs like AESGCM.decrypt guarantee this. Streaming APIs that release plaintext chunks before the final tag check need care.
  4. Separate keys for separate purposes. Derive them with HKDF (KDFs versus Password Hashes).

Nonce-misuse-resistant AEADs such as AES-GCM-SIV (RFC 8452) limit the damage of an accidental repeat to revealing that two messages were equal. They are worth considering where nonce uniqueness is hard to guarantee.

How AEAD misuse is detected

  • Code review: a constant or derived nonce (nonce = b"\x00" * 12, nonce = key[:12], nonce = hash(message)), a nonce counter kept in memory and reset on restart, the same key shared between many hosts that each pick nonces with their own counters.
  • Key-usage accounting: how many messages has this key encrypted? A service that encrypts billions of records under one GCM key with random nonces is past the 2^32 guideline.
  • Data inspection: extract the nonces stored with ciphertexts (usually the first 12 bytes) and count duplicates per key: SELECT nonce, COUNT(*) FROM vault GROUP BY key_id, nonce HAVING COUNT(*) > 1.
  • Error handling: code that catches InvalidTag and carries on with partial data or a default value.

How it is fixed

  • AESGCM or ChaCha20Poly1305 with os.urandom(12) per message and a key rotated well before 2^32 messages, or a persistent counter nonce per key; XChaCha20-Poly1305 or AES-GCM-SIV where unique nonces are hard.
  • Put the context (version, record id, user id) in the AAD.
  • Treat any InvalidTag as an attack or corruption: stop, log, alert; never "best effort" decrypt.

Pitfalls

  • Truncating tags to save space. GCM allows shorter tags, and each removed byte makes forgery 256 times easier; keep 16 bytes.
  • Thinking AAD is encrypted. It is sent in the clear.
  • Encrypting huge files as one GCM message: AES-GCM is limited to about 64 GiB per message (2^39 − 256 bits), and you can't verify before reading everything. Split into chunks, each bound to its position (chunk index and a "last chunk" flag, in the nonce or the AAD), so chunks can't be reordered or dropped (libsodium's secretstream and the age format work this way).

Practice

1. A service stores encrypted user notes as nonce || ciphertext || tag. How would an attacker with database write access swap two users' notes, and how does AAD prevent it?

Without AAD, copying Alice's row into Bob's row decrypts fine for Bob: same key, valid tag. With the user id (or row id) in the AAD, the tag only verifies for the original owner, and the swapped ciphertext fails with InvalidTag.

2. Which is safer for a fleet of 500 servers sharing one key: random 96-bit nonces or a per-server counter starting at 0?

Random nonces (within the per-key message limit), or counters with a server id in the nonce. Counters starting at 0 on every server collide immediately: server 1's message 0 and server 2's message 0 share a nonce.

3. In the example, what happens if you decrypt with the right key and AAD but nonce ...02?

InvalidTag. The nonce is an input to both the keystream and the tag, so a wrong nonce fails like any other change.

Test yourself

What is associated data (AAD) in an AEAD?

  1. Data that is encrypted twice
  2. Data that is authenticated but not encrypted
  3. The nonce
  4. The key identifier, which is secret

How much longer than the plaintext was each AEAD ciphertext in the example?

  1. 0 bytes
  2. 12 bytes
  3. 16 bytes
  4. 32 bytes

What is the single most important rule for AES-GCM?

  1. Keep the nonce secret
  2. Never reuse a nonce with the same key
  3. Use a 256-bit key only
  4. Encrypt the AAD

Why might ChaCha20-Poly1305 be preferred on a low-end phone CPU?

  1. It has a larger tag
  2. It is fast and constant-time in pure software, without AES hardware
  3. It needs no nonce
  4. It is post-quantum