Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 40 ยท Symmetric Encryption

Authenticated Encryption: GCM and ChaCha20-Poly1305

Learn why encryption alone is not enough, build a toy encrypt-then-MAC AEAD in Python, and watch bit-flipping and padding-oracle attacks fail against it.

Every cipher so far hides the content of a message but says nothing about whether the message arrived unchanged. As the last lesson showed, an attacker can flip bits in a CTR or CBC ciphertext and change the plaintext in predictable ways, without ever learning the key. Worse, an application that reacts differently to different kinds of decryption failures can be turned into an oracle that gives the plaintext away completely.

Authenticated encryption with associated data, usually abbreviated AEAD, is the modern answer. A single operation encrypts the message and attaches an authentication tag. On decryption the tag is verified first; if anything was altered, the whole message is rejected and no plaintext is released. AES-GCM and ChaCha20-Poly1305 are the two AEAD ciphers that protect almost all TLS traffic today. In this lesson you will see the attacks that motivate AEAD, build a small AEAD yourself from a stream cipher and HMAC, and learn the rules for using the real thing.

The interface of an AEAD

An AEAD has two functions:

  • seal(key, nonce, plaintext, aad) -> ciphertext || tag
  • open(key, nonce, ciphertext || tag, aad) -> plaintext (or an error)

The associated data (AAD) is information that is authenticated but not encrypted: a packet header, a user ID, a protocol version, a message sequence number. It must be readable by the network, yet it must not be modifiable or moved from one message to another. The tag covers the ciphertext and the AAD together, so changing either one makes open fail.

flowchart LR
    K["Key"] --> S["seal"]
    N["Nonce"] --> S
    P["Plaintext"] --> S
    A["Associated data<br/>(header, not encrypted)"] --> S
    S --> C["Ciphertext"]
    S --> T["Tag"]

An AEAD encrypts the plaintext and produces a tag that covers both the ciphertext and the header.

Why encryption alone fails: bit flipping

Take the plain stream-cipher approach from earlier. The attacker knows (or guesses) the format of the message, and flips exactly the ciphertext bits that turn one character into another.

Python Editing a ciphertext without the key

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The receiver sees a valid-looking message for $9050. Nothing in the cipher could notice, because every bit pattern is a legal ciphertext.

Building a toy AEAD: encrypt-then-MAC

The safest generic recipe is encrypt-then-MAC: encrypt first, then compute a message authentication code over the ciphertext (plus nonce and associated data), and append it. The receiver recomputes the MAC before decrypting and discards the message on mismatch. Two details matter:

  1. Separate keys. Derive one key for encryption and one for the MAC from the master key, never reuse one key for both jobs.
  2. Unambiguous input to the MAC. Include the lengths of the variable-size parts, so an attacker cannot shift bytes from the header into the ciphertext without changing the MAC input.

The toy below uses a hash-based keystream for encryption and HMAC-SHA256 truncated to 16 bytes for the tag. It follows the same pattern as real AEAD designs, though it is not a standard one.

Python A toy encrypt-then-MAC AEAD

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Every modification is rejected, and no plaintext is ever returned for a bad message. Note the header: it was never encrypted, yet changing it breaks the tag. That is the point of associated data. The compare_digest call is a constant-time comparison; the MACs lesson explains why that matters.

The padding oracle attack

Padded CBC has a more dangerous failure than bit flipping. Suppose a server decrypts incoming ciphertexts and answers differently, even just through timing or an error code, for "the padding is invalid" versus "the padding is fine but the content is garbage". That tiny difference is an oracle: it answers "does this ciphertext decrypt to something ending in valid padding?"

An attacker uses it to recover plaintext one byte at a time. In CBC, plaintext block = D(C_i) XOR C_(i-1), where D(C_i) is the intermediate value inside the cipher. By sending a forged previous block and asking the oracle whether the result has valid padding, the attacker finds the value that makes the last byte equal 0x01, which reveals the intermediate byte; then she aims for 0x02 0x02, and so on. With at most 256 guesses per byte she reconstructs every block. The key is never needed.

The experiment below attacks a real working CBC implementation (using the toy block cipher from the last lesson) by using nothing but the oracle.

Python A padding oracle recovers the plaintext

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The attack recovers the whole 24-byte message, and even its padding bytes, in 3,896 queries. The defence in the last lines shows the principle: because the MAC is verified before any decryption or padding check, every forged ciphertext is rejected in the same way, and the oracle shows nothing. This is why modern guidance says to verify first, decrypt second, and why AEAD ciphers exist: they bake that rule in.

The two AEAD ciphers you will use

AES-GCM combines AES in counter mode with GHASH, a polynomial-evaluation authenticator over the finite field GF(2128). It is extremely fast on processors with AES instructions. Use a 96-bit (12-byte) nonce and a 128-bit tag. ChaCha20-Poly1305 combines the ChaCha20 stream cipher with the Poly1305 authenticator, and is fast in plain software, which suits phones and small devices. TLS 1.3 supports both.

Both share the same critical rule: never reuse a nonce with the same key. In GCM, a repeated nonce reveals the XOR of the plaintexts and also lets an attacker recover the authentication key, so she can forge messages. For random nonces, rotate the key long before about 232 messages under it.

With Python's cryptography package (not available in your browser here, so this is read-only), the whole toy above becomes:

Python
import os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM, ChaCha20Poly1305

key = AESGCM.generate_key(bit_length=256)
aead = AESGCM(key)

nonce = os.urandom(12)                       # a new random nonce for every message
header = b"user=42;version=3"
blob = aead.encrypt(nonce, b"PAY $0050 TO ALICE", header)   # ciphertext + 16-byte tag

print(aead.decrypt(nonce, blob, header))     # original plaintext
# Any change to blob, nonce or header raises cryptography.exceptions.InvalidTag

chacha = ChaCha20Poly1305(ChaCha20Poly1305.generate_key())

Notice how little there is to get wrong: no padding, no IV choice, no separate MAC. You supply a unique nonce, and the library does the rest. Compare this to composing the pieces yourself, as we did above for teaching.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is 'associated data' in an AEAD?

    Associated data is covered by the tag, so it cannot be changed or moved to another message, but it is not hidden. Headers and user IDs are typical examples.
  2. 2. In encrypt-then-MAC, what does the receiver do first?

    Verifying before decrypting means tampered messages are rejected without touching the plaintext, which also shuts down padding-oracle attacks.
  3. 3. Why does a padding oracle attack work against CBC without authentication?

    Each yes/no answer about padding confirms or rules out a guess for one intermediate byte, so each byte falls to at most 256 queries.
  4. 4. What is the most important rule when using AES-GCM or ChaCha20-Poly1305?

    A repeated nonce reuses the keystream and, in GCM, can expose the authentication key, breaking both secrecy and integrity.

Summary

  • Encryption alone does not detect tampering; bit flipping and padding oracles exploit that.
  • AEAD ciphers (AES-GCM, ChaCha20-Poly1305) encrypt, authenticate the ciphertext and the associated data, and return a tag; open fails closed.
  • Encrypt-then-MAC with separate keys and length-prefixed input is the safe generic construction.
  • Verify the tag before decrypting, compare tags in constant time, and never repeat a nonce under one key.

Next: MACs and HMAC, the authentication primitive hiding inside every AEAD.