Authenticated Encryption
AES-GCM, ChaCha20-Poly1305, and AEAD
Skills taught: crypto.aead
AEAD: Authenticated Encryption with Associated Data
AEAD schemes provide both confidentiality and integrity in one operation. If the ciphertext is tampered with, decryption raises an error — you never see corrupted plaintext. This is the correct default for all modern encryption.
- Authentication Tag
- A short value (usually 16 bytes for GCM) appended to the ciphertext. If even one bit of the ciphertext is flipped, the tag fails to verify and decryption is refused.
- Associated Data (AAD)
- Data that is authenticated but not encrypted. Useful for headers, metadata, or IDs that must travel with the ciphertext and must not be modified independently.
AES-GCM in Practice
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
import os
# --- Key setup ---
key = AESGCM.generate_key(bit_length=256) # one key, reused with different nonces
aesgcm = AESGCM(key)
# --- Encrypt ---
nonce = os.urandom(12) # unique 12-byte nonce per message
aad = b"user_id:1234" # authenticated but not encrypted
plaintext = b"Account balance: $5000"
ciphertext = aesgcm.encrypt(nonce, plaintext, aad)
print("Ciphertext:", ciphertext.hex()) # plaintext + 16-byte tag
# --- Decrypt (happy path) ---
recovered = aesgcm.decrypt(nonce, ciphertext, aad)
print("Decrypted:", recovered) # b'Account balance: $5000'
# --- Tampered ciphertext ---
tampered = bytearray(ciphertext)
tampered[5] ^= 0x01 # flip one bit
try:
aesgcm.decrypt(nonce, bytes(tampered), aad)
except Exception as e:
print("Tampering detected:", e) # InvalidTag
# --- Wrong AAD ---
try:
aesgcm.decrypt(nonce, ciphertext, b"user_id:9999")
except Exception:
print("AAD mismatch detected") # attacker cannot change the AAD
Warning: Never reuse a nonce with the same AES-GCM key. Even one reuse exposes the keystream and allows the attacker to forge authentication tags. Use os.urandom(12) for every message, or use a counter-based nonce scheme.
ChaCha20-Poly1305: The Software-First Alternative
ChaCha20-Poly1305 is an AEAD scheme designed by Daniel Bernstein. It provides equivalent security to AES-GCM but is faster on systems without AES hardware acceleration (many ARM devices, IoT hardware).
from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
import os
key = ChaCha20Poly1305.generate_key() # 32 bytes
nonce = os.urandom(12) # 96-bit nonce
chacha = ChaCha20Poly1305(key)
ciphertext = chacha.encrypt(nonce, b"Encrypted message", None)
plaintext = chacha.decrypt(nonce, ciphertext, None)
print(plaintext)
AES-256-GCM vs ChaCha20-Poly1305
- AES-256-GCM: Block cipher AEAD; hardware-accelerated on modern CPUs
- ChaCha20-Poly1305: Stream cipher AEAD; fast in software
File Encryption with AEAD
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
import os
def encrypt_file(key: bytes, path_in: str, path_out: str) -> None:
nonce = os.urandom(12)
aesgcm = AESGCM(key)
with open(path_in, "rb") as f:
data = f.read()
ciphertext = aesgcm.encrypt(nonce, data, None)
with open(path_out, "wb") as f:
f.write(nonce + ciphertext) # prepend nonce so it travels with ciphertext
def decrypt_file(key: bytes, path_in: str) -> bytes:
aesgcm = AESGCM(key)
with open(path_in, "rb") as f:
raw = f.read()
nonce = raw[:12]
ciphertext = raw[12:]
return aesgcm.decrypt(nonce, ciphertext, None)
key = AESGCM.generate_key(256)
encrypt_file(key, "report.pdf", "report.pdf.enc")
original = decrypt_file(key, "report.pdf.enc")
Tip: Prepend the nonce to the ciphertext — the nonce is not secret, just unique. Format: nonce (12 bytes) | ciphertext | tag (16 bytes). The receiver extracts the first 12 bytes as the nonce.
Frequently Asked Questions
What is the associated data (AAD) used for?
AAD is authenticated but not encrypted. It is useful for headers or metadata you need to verify (like a user ID, record version, or API endpoint) without encrypting them. If AAD is modified, decryption fails.
Should I store the nonce with the ciphertext?
Yes. The nonce is not secret — it only needs to be unique. The standard format is: nonce (12 bytes) | ciphertext | authentication tag (16 bytes). Store or transmit all three together.
What happens if AES-GCM authentication fails?
The cryptography library raises an InvalidTag exception. You should NEVER fall back to returning the ciphertext if the tag fails. Treat InvalidTag as a critical security event and reject the message.