Authenticated Encryption and Signatures in Code
Solve two real requirements end to end: encrypt backup files with AES-256-GCM so any change is detected, and sign software updates with Ed25519 so an agent installs only genuine, newer builds. Every attack in the lesson is run and must fail.
Contentsand lesson path
On this page
- The problem
- Step 1: seal a backup with AES-256-GCM
- Step 2: attack the sealed file
- Step 3: sign updates with Ed25519
- Step 4: attack the update channel
- Check your understanding
- Apply it
- Review prompt
Lessons of Applied Cryptography
- Matching Primitives to Security Requirements Concept · 20 min
- Authenticated Encryption and Signatures in Code Worked example · 25 min
- Password Storage That Survives a Database Leak Lab · 25 min
- Key Lifecycle and Envelope Encryption Concept · 20 min
- Spotting Crypto Misuse and Planning for Post-Quantum Worked example · 20 min
- Applied Cryptography Check Knowledge check · 8 questions
What you will learn
- Select the right primitive (authenticated encryption, hash, MAC, digital signature or key exchange) for a stated security requirement and justify the choice.
01. The problem
A small dental group runs a backup agent at each clinic. Every night the agent exports the appointment database and uploads it to cloud storage. The vendor of the agent ships updates to it. Two requirements come out of a short risk discussion.
- Backups: the storage provider, or anyone who steals the bucket credentials, must not be able to read a backup, and must not be able to change one, or move one clinic's file into another clinic's slot, without the restore noticing. Only the clinic's own agent creates and reads backups.
- Updates: every clinic must be able to check that an update really came from the vendor, and no clinic, and no attacker who copies a clinic's files, may be able to produce an update that passes the check. An old genuine update must not be accepted again as a "new" one.
Apply the questions from Matching Primitives to Security Requirements. For backups, one party both creates and reads, and it needs secrecy plus tamper detection: that is authenticated encryption with a key only the agent holds. For updates, one party creates and many check, and the checkers must not gain the power to create: that is a digital signature. The version rule is a freshness requirement, which needs a check on top of the signature.
Work in a new folder with the same environment as the previous lesson: Python 3.12 and cryptography==50.0.2 in a uv virtual environment.
mkdir backup-lab && cd backup-lab
uv venv --python 3.12 .venv && source .venv/bin/activate
uv pip install "cryptography==50.0.2"02. Step 1: seal a backup with AES-256-GCM
AES-GCM takes four inputs: a key, a nonce (a number used once), the plaintext and optional associated data. Associated data, often shortened to AAD, is not encrypted but is protected by the tag: change it and decryption fails. That makes AAD the right place for metadata that must stay readable, such as which clinic and which file a backup belongs to. If you leave the header out of the AAD, an attacker can attach a genuine ciphertext to a different header.
The nonce does not need to be secret, so it is stored next to the ciphertext. What it needs is to be unique for every encryption under the same key. With 12 random bytes per message, NIST SP 800-38D (section 8.3) caps one key at 2^32 encryptions, so a long-lived system counts its messages and rotates the key well before that limit.
"""Seal and open backup files with AES-256-GCM, binding a header as associated data."""
import base64
import json
import os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
def _aad(header: dict) -> bytes:
# Canonical bytes: the same header must always give the same AAD.
return json.dumps(header, sort_keys=True, separators=(",", ":")).encode()
def seal(key: bytes, header: dict, data: bytes) -> str:
nonce = os.urandom(12) # 96 bits, fresh for every message under this key
ct = AESGCM(key).encrypt(nonce, data, _aad(header))
return json.dumps({
"header": header,
"nonce": base64.b64encode(nonce).decode(),
"ct": base64.b64encode(ct).decode(),
})
def open_sealed(key: bytes, blob: str) -> bytes:
box = json.loads(blob)
nonce = base64.b64decode(box["nonce"])
ct = base64.b64decode(box["ct"])
# Raises cryptography.exceptions.InvalidTag if anything was changed.
return AESGCM(key).decrypt(nonce, ct, _aad(box["header"]))Two details deserve attention. First, _aad serialises the header with sorted keys and no spaces. The AAD must be the same bytes at encryption and decryption time, and a dictionary printed in a different order is a different byte string. Second, open_sealed returns nothing but the plaintext or an exception. GCM checks the tag before releasing any data, so you never handle "partly decrypted" bytes.
03. Step 2: attack the sealed file
A security test that only checks the happy path proves very little. The script below performs a round trip and then three attacks that an attacker with access to the bucket could try: flip a ciphertext bit, move the file to another clinic by editing the header, and decrypt with a different key.
"""Round trip, then three attacks that must fail."""
import base64
import json
from cryptography.exceptions import InvalidTag
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from seal import open_sealed, seal
key = AESGCM.generate_key(bit_length=256)
header = {"clinic": "north-street", "file": "2026-11-15.sql", "v": 1}
blob = seal(key, header, b"INSERT INTO patients VALUES (...);")
print("round trip:", open_sealed(key, blob) == b"INSERT INTO patients VALUES (...);")
print("nonce bytes:", len(base64.b64decode(json.loads(blob)["nonce"])))
def attempt(name: str, k: bytes, b: str) -> None:
try:
open_sealed(k, b)
print(f"{name:<22} ACCEPTED <- this would be a bug")
except InvalidTag:
print(f"{name:<22} rejected: InvalidTag")
box = json.loads(blob)
ct = bytearray(base64.b64decode(box["ct"]))
ct[3] ^= 0x01 # flip one bit of the ciphertext
flipped = {**box, "ct": base64.b64encode(ct).decode()}
attempt("flipped ciphertext bit", key, json.dumps(flipped))
moved = {**box, "header": {**header, "clinic": "south-road"}}
attempt("header swapped", key, json.dumps(moved))
attempt("wrong key", AESGCM.generate_key(bit_length=256), blob)python try_seal.pyround trip: True
nonce bytes: 12
flipped ciphertext bit rejected: InvalidTag
header swapped rejected: InvalidTag
wrong key rejected: InvalidTagAll three attacks end in the same exception, InvalidTag, and that is deliberate. The library does not tell you why the tag failed, because a detailed error would help an attacker. Your code should treat every InvalidTag as "this file is not trustworthy", log it, and stop.
If the clinic servers lack AES hardware acceleration, ChaCha20-Poly1305 gives the same guarantees and is fast in software. The interface is identical, so switching is a one-line change.
"""ChaCha20-Poly1305 has the same AEAD interface: key, 12-byte nonce, data, AAD."""
import os
from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
key = ChaCha20Poly1305.generate_key()
nonce = os.urandom(12)
ct = ChaCha20Poly1305(key).encrypt(nonce, b"same API, different cipher", b"hdr")
print("tag adds 16 bytes:", len(ct) - len(b"same API, different cipher"))
print("round trip:", ChaCha20Poly1305(key).decrypt(nonce, ct, b"hdr"))python chacha.pytag adds 16 bytes: 16
round trip: b'same API, different cipher'04. Step 3: sign updates with Ed25519
The vendor signs a small manifest rather than the whole update. The manifest names the product, gives a version number and holds the SHA-256 of the update file. Signing the manifest binds all three together: change the file and its hash no longer matches, change the version and the signature fails. Ed25519 is a good default signature scheme: keys and signatures are small, signing is deterministic (no random nonce to get wrong) and the API has no parameters to misconfigure.
In this lab the vendor script creates its key on each run, for simplicity. A real vendor generates the key once, keeps it in a hardware security module or a KMS signing key, and publishes the public key with the agent.
"""Vendor side: sign an update manifest with Ed25519 (the private key stays here)."""
import hashlib
import json
from pathlib import Path
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
signing_key = Ed25519PrivateKey.generate()
Path("vendor_public.pem").write_bytes(signing_key.public_key().public_bytes(
serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo))
def release(version: int, payload: bytes) -> None:
Path(f"agent-{version}.bin").write_bytes(payload)
manifest = json.dumps({"name": "backup-agent", "version": version,
"sha256": hashlib.sha256(payload).hexdigest()},
sort_keys=True).encode()
Path(f"agent-{version}.manifest").write_bytes(manifest)
Path(f"agent-{version}.sig").write_bytes(signing_key.sign(manifest))
release(7, b"agent build 7")
release(8, b"agent build 8")
print("released versions 7 and 8; public key in vendor_public.pem")"""Agent side: verify before trusting anything in the update."""
import hashlib
import json
import sys
from pathlib import Path
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import serialization
PINNED = serialization.load_pem_public_key(Path("vendor_public.pem").read_bytes())
INSTALLED_VERSION = 7
def check(manifest: bytes, sig: bytes, payload: bytes) -> str:
try:
PINNED.verify(sig, manifest) # 1. signature first, before parsing
except InvalidSignature:
return "reject: bad signature"
meta = json.loads(manifest)
if hashlib.sha256(payload).hexdigest() != meta["sha256"]:
return "reject: payload does not match manifest"
if meta["version"] <= INSTALLED_VERSION:
return f"reject: version {meta['version']} is not newer"
return f"install version {meta['version']}"
v = sys.argv[1]
files = [Path(f"agent-{v}.{ext}").read_bytes() for ext in ("manifest", "sig", "bin")]
print(check(*files))python release.py
python install.py 8
python install.py 7released versions 7 and 8; public key in vendor_public.pem
install version 8
reject: version 7 is not newerVersion 7 is genuine and correctly signed, and it is still refused. That is the freshness check from step 3 of check: without it, an attacker who saved an old update with a known vulnerability could "downgrade" every clinic to it, and the signature would verify perfectly. A real agent stores the installed version somewhere the update process cannot be tricked into lowering.
Notice also what the agent holds: vendor_public.pem and nothing else. The public key is pinned, which means it is shipped with the agent and not downloaded alongside each update. If the agent fetched the key from the same server as the update, an attacker who controls that server would simply supply their own key.
05. Step 4: attack the update channel
Now act as an attacker who can write to the download server but does not have the vendor's private key. Attack A keeps the genuine manifest and signature for version 8 but swaps the file. Attack B invents version 9 and signs it with a key the attacker generated.
"""Two forged updates, each built by someone without the vendor's private key."""
import hashlib
import json
from pathlib import Path
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
# A: keep the real signature but swap the payload.
Path("agent-8.bin").write_bytes(b"agent build 8 with a backdoor")
# B: sign a new manifest with the attacker's own key.
evil_hash = hashlib.sha256(b"evil").hexdigest()
fake = {"name": "backup-agent", "version": 9, "sha256": evil_hash}
evil = json.dumps(fake, sort_keys=True).encode()
Path("agent-9.bin").write_bytes(b"evil")
Path("agent-9.manifest").write_bytes(evil)
Path("agent-9.sig").write_bytes(Ed25519PrivateKey.generate().sign(evil))
print("forged updates written")python attack_update.py
python install.py 8
python install.py 9forged updates written
reject: payload does not match manifest
reject: bad signatureAttack A passes the signature check, because the manifest really is the vendor's, and is stopped by the hash comparison. Attack B fails at the first line: a signature made with any key other than the pinned one is just random bytes to the verifier. Between them, the two attacks show why each part of check exists. Run python release.py again whenever you want to restore the genuine files.
06. Check your understanding
07. Apply it
In your file-encryption CLI, implement seal and open for files using AES-256-GCM, with the file name, a format version and a key id in the associated data. Write tests that must fail: a flipped byte, a renamed file whose header was edited, and a wrong key. Then add a signed release manifest for the CLI itself and a test that rejects an older version.
08. Review prompt
From memory: list the four inputs to AES-GCM and say which one must never repeat under a key and why the nonce can be stored in clear. Then write the three checks an update agent performs, in order, and name the attack that each one stops.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.