Spotting Crypto Misuse and Planning for Post-Quantum
Review a real-looking pull request with seven cryptographic mistakes, find them by reading and with a small pattern checker, rewrite the code, and prove the fix with tests that must refuse bad input. Then turn the same inventory into a post-quantum migration plan and run ML-KEM-768.
Contentsand lesson path
On this page
- The problem
- Step 1: read it like a reviewer
- Step 2: back up your reading with a checker
- Step 3: rewrite and prove the fix
- Step 4: plan the post-quantum migration
- 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
- Identify cryptographic misuse in code or configuration, such as ECB mode, nonce reuse, weak randomness or disabled certificate validation, propose a fix, and outline post-quantum migration readiness.
01. The problem
You are asked to review a pull request for a small finance service. It adds four features: encrypted data exports, encrypted messages between two internal services, password-reset tokens and a client for an internal exchange-rates API. A second file signs requests to a partner and agrees session keys with it. The code runs and its unit tests pass, which is exactly why cryptographic mistakes survive: almost none of them break the happy path.
Your job has two parts. First, find each misuse, explain the risk and propose a fix. Second, the security lead wants to know which parts of the service depend on public-key algorithms that a future quantum computer could break, and what to do about them.
Create the folders and environment below: app/ holds the code under review and fixed/ your rewrite. The code under review is only read and scanned, never run.
mkdir -p review/app review/fixed && cd review
uv venv --python 3.12 .venv && source .venv/bin/activate
uv pip install "cryptography==50.0.2""""Pull request under review: export encryption, messages, tokens, an API client."""
import hashlib
import random
import ssl
import requests
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
KEY = bytes.fromhex("00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff")
NONCE = b"\x00" * 12
def encrypt_export(data: bytes) -> bytes:
enc = Cipher(algorithms.AES(KEY), modes.ECB()).encryptor()
return enc.update(data) + enc.finalize()
def encrypt_message(data: bytes) -> bytes:
return AESGCM(KEY).encrypt(NONCE, data, None)
def reset_token() -> str:
alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"
return "".join(random.choice(alphabet) for _ in range(24))
def file_fingerprint(data: bytes) -> str:
return hashlib.md5(data).hexdigest()
def fetch_rates() -> dict:
return requests.get("https://rates.internal.example/v1", verify=False).json()
def client_context() -> ssl.SSLContext:
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
return ctx"""Partner API signing and key agreement (also part of the PR)."""
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa
def new_signing_key() -> rsa.RSAPrivateKey:
return rsa.generate_private_key(public_exponent=65537, key_size=2048)
def sign(key: rsa.RSAPrivateKey, data: bytes) -> bytes:
return key.sign(data, padding.PSS(padding.MGF1(hashes.SHA256()),
padding.PSS.MAX_LENGTH), hashes.SHA256())
def agree(peer_public: ec.EllipticCurvePublicKey) -> bytes:
mine = ec.generate_private_key(ec.SECP256R1())
return mine.exchange(ec.ECDH(), peer_public)02. Step 1: read it like a reviewer
Read storage.py before using any tool, and for each function ask what the code promises and what it actually guarantees.
KEYin the source. Anyone with the repository, a build log or the container image has the key. The fix is the envelope design from Key Lifecycle and Envelope Encryption, and the committed key must be treated as exposed.modes.ECB(). Electronic codebook mode encrypts each 16-byte block on its own, so equal plaintext blocks become equal ciphertext blocks. Repeated structure in an export, such as identical salary fields, shows through, and nothing detects changes. The fix is AES-GCM.- A constant
NONCE. AES-GCM is safe only when each nonce is used once per key. With a fixed nonce every message is encrypted with the same keystream, so XOR-ing two ciphertexts gives the XOR of the two plaintexts, and an attacker can compute valid tags for messages of their own; NIST SP 800-38D treats nonce uniqueness as a hard requirement. The fix is a fresh 12-byte random nonce per message, stored with the ciphertext. random.choicefor tokens. Python'srandommodule is a fast simulation generator whose internal state can be reconstructed from enough output; its documentation says it must not be used for security purposes. The fix is thesecretsmodule.- MD5 fingerprints. Practical MD5 collisions mean someone can prepare two different files with the same fingerprint. Use SHA-256, and deliver the fingerprint over a trusted channel or sign it.
verify=Falseand 7.CERT_NONEwithcheck_hostname = False. Both switch off the part of TLS that proves who you are talking to. The connection is still encrypted, but to whoever answered, so anyone able to intercept the traffic can present their own certificate. The usual cause is a private CA that the client does not trust yet; the fix is to give the client that CA, not to stop checking.
signing.py has no misuse: RSA-PSS with SHA-256 and ephemeral ECDH on P-256 are sound choices today. It appears again in step 4, because both algorithms are quantum-vulnerable.
03. Step 2: back up your reading with a checker
Reviewers pair reading with automated checks. Real projects use tools such as Semgrep or Bandit, which ship rules for these patterns. The helper below does the same job in miniature: one regular expression per known misuse, plus a second list that records every use of quantum-vulnerable public-key algorithms for the inventory in step 4.
"""A small reviewer's helper: flag known crypto misuse and list quantum-vulnerable use.
It matches patterns line by line, so it finds candidates for a human to read; it
cannot prove code is safe. Real projects use Semgrep or Bandit rules the same way.
"""
import re
import sys
from pathlib import Path
MISUSE = [
(r"modes\.ECB\(", "ECB mode leaks repeated blocks", "use AESGCM, fresh nonce"),
(r"NONCE\s*=\s*b[\"']", "constant nonce", "os.urandom(12) per message"),
(r"\brandom\.(choice|random|randint|getrandbits)", "non-cryptographic RNG",
"use the secrets module"),
(r"hashlib\.(md5|sha1)\(", "broken hash for integrity", "use hashlib.sha256"),
(r"verify\s*=\s*False", "TLS certificate check disabled", "pass a CA bundle"),
(r"CERT_NONE|check_hostname\s*=\s*False", "TLS verification disabled",
"keep create_default_context() defaults"),
(r"(KEY|SECRET)\s*=\s*(bytes\.fromhex|b[\"'])", "hard-coded key", "use a KMS"),
]
QUANTUM_VULNERABLE = [
(r"rsa\.generate_private_key", "RSA"),
(r"ec\.ECDH\(|ec\.generate_private_key", "elliptic-curve (ECDH/ECDSA)"),
(r"X25519|Ed25519", "Curve25519 (X25519/Ed25519)"),
]
findings, inventory = 0, []
for path in sorted(Path(sys.argv[1]).rglob("*.py")):
for n, line in enumerate(path.read_text().splitlines(), 1):
for pattern, problem, fix in MISUSE:
if re.search(pattern, line):
findings += 1
print(f"{path}:{n}: {problem} -> {fix}")
for pattern, family in QUANTUM_VULNERABLE:
if re.search(pattern, line):
inventory.append(f"{path}:{n}: {family}")
print(f"{findings} misuse findings")
print("quantum-vulnerable public-key use (plan migration):")
for item in inventory:
print(" " + item)python crypto_lint.py appapp/storage.py:10: hard-coded key -> use a KMS
app/storage.py:11: constant nonce -> os.urandom(12) per message
app/storage.py:15: ECB mode leaks repeated blocks -> use AESGCM, fresh nonce
app/storage.py:25: non-cryptographic RNG -> use the secrets module
app/storage.py:29: broken hash for integrity -> use hashlib.sha256
app/storage.py:33: TLS certificate check disabled -> pass a CA bundle
app/storage.py:38: TLS verification disabled -> keep create_default_context() defaults
app/storage.py:39: TLS verification disabled -> keep create_default_context() defaults
8 misuse findings
quantum-vulnerable public-key use (plan migration):
app/signing.py:7: RSA
app/signing.py:16: elliptic-curve (ECDH/ECDSA)
app/signing.py:17: elliptic-curve (ECDH/ECDSA)The checker found the seven problems you read about (lines 38 and 39 are one mistake). A pattern checker is a safety net, not a verdict. It would not notice a nonce that comes from a counter reset on every restart, a key reused for two purposes, or associated data that leaves out the tenant id.
04. Step 3: rewrite and prove the fix
The safe versions are mostly the library defaults. The key is now a parameter supplied by the caller, who gets it from the KMS. For the private CA, client_context takes a CA file and keeps every other default of ssl.create_default_context(), which checks both the certificate chain and the hostname.
"""The same features after review."""
import hashlib
import os
import secrets
import ssl
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
def seal(key: bytes, data: bytes, aad: bytes) -> bytes:
nonce = os.urandom(12) # fresh for every message; stored in front of the output
return nonce + AESGCM(key).encrypt(nonce, data, aad)
def unseal(key: bytes, blob: bytes, aad: bytes) -> bytes:
return AESGCM(key).decrypt(blob[:12], blob[12:], aad)
def reset_token() -> str:
return secrets.token_urlsafe(32) # 32 random bytes from the OS CSPRNG
def file_fingerprint(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def client_context(ca_file: str | None = None) -> ssl.SSLContext:
# Defaults verify the chain and the hostname. Trust a private CA by adding it,
# never by switching verification off.
return ssl.create_default_context(cafile=ca_file)To test certificate checking honestly you need a server whose certificate is not trusted by default. The next script creates a throwaway lab CA and a server certificate for localhost and 127.0.0.1, both valid for one day. The test then runs a TLS server on 127.0.0.1 port 8112 and connects three times: once trusting only the system store, once with the lab CA and the right name, and once with the lab CA and the wrong name.
"""A throwaway lab CA and a server certificate for 127.0.0.1 / localhost."""
import datetime as dt
import ipaddress
from pathlib import Path
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.x509.oid import NameOID
now = dt.datetime.now(dt.timezone.utc)
def name(cn: str) -> x509.Name:
return x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, cn)])
ca_key = ec.generate_private_key(ec.SECP256R1())
ca = (x509.CertificateBuilder().subject_name(name("Lab CA")).issuer_name(name("Lab CA"))
.public_key(ca_key.public_key()).serial_number(x509.random_serial_number())
.not_valid_before(now).not_valid_after(now + dt.timedelta(days=1))
.add_extension(x509.BasicConstraints(ca=True, path_length=0), critical=True)
.add_extension(x509.KeyUsage(False, False, False, False, False, True, True,
False, False), critical=True)
# key identifiers: Python 3.13+ verifies strictly and needs them
.add_extension(x509.SubjectKeyIdentifier.from_public_key(ca_key.public_key()),
critical=False)
.sign(ca_key, hashes.SHA256()))
srv_key = ec.generate_private_key(ec.SECP256R1())
san = x509.SubjectAlternativeName([x509.DNSName("localhost"),
x509.IPAddress(ipaddress.ip_address("127.0.0.1"))])
srv = (x509.CertificateBuilder().subject_name(name("localhost")).issuer_name(ca.subject)
.public_key(srv_key.public_key()).serial_number(x509.random_serial_number())
.not_valid_before(now).not_valid_after(now + dt.timedelta(days=1))
.add_extension(san, critical=False)
.add_extension(x509.SubjectKeyIdentifier.from_public_key(srv_key.public_key()),
critical=False)
.add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(
ca_key.public_key()), critical=False)
.sign(ca_key, hashes.SHA256()))
pem = serialization.Encoding.PEM
Path("lab_ca.pem").write_bytes(ca.public_bytes(pem))
Path("server.pem").write_bytes(srv.public_bytes(pem))
Path("server.key").write_bytes(srv_key.private_bytes(
pem, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()))
print("wrote lab_ca.pem, server.pem, server.key (valid for one day)")"""Tests for the reviewed code, including cases that must be refused."""
import socket
import ssl
import threading
from cryptography.exceptions import InvalidTag
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from fixed.storage import client_context, reset_token, seal, unseal
key = AESGCM.generate_key(bit_length=256)
a, b = seal(key, b"same text", b"export"), seal(key, b"same text", b"export")
print("same plaintext, different ciphertext:", a != b)
print("both decrypt:", unseal(key, a, b"export") == unseal(key, b, b"export"))
try:
unseal(key, a[:-1] + bytes([a[-1] ^ 1]), b"export")
except InvalidTag:
print("tampered message refused: InvalidTag")
tokens = {reset_token() for _ in range(1000)}
print("1000 tokens, all distinct:", len(tokens) == 1000, "| length:", len(tokens.pop()))
# A local TLS server on 127.0.0.1:8112 using the lab certificate.
server_ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
server_ctx.load_cert_chain("server.pem", "server.key")
listener = socket.create_server(("127.0.0.1", 8112))
def serve() -> None:
for _ in range(3):
conn, _ = listener.accept()
try:
with server_ctx.wrap_socket(conn, server_side=True) as tls:
tls.sendall(b"hello")
except (ssl.SSLError, OSError):
pass # the client gave up during the handshake
threading.Thread(target=serve, daemon=True).start()
def connect(ctx: ssl.SSLContext, host: str) -> str:
try:
with socket.create_connection(("127.0.0.1", 8112)) as raw:
with ctx.wrap_socket(raw, server_hostname=host) as tls:
return f"connected, {tls.version()}, got {tls.recv(5)!r}"
except ssl.SSLCertVerificationError as err:
return "refused: " + err.verify_message.split(",")[0]
lab = client_context("lab_ca.pem")
print("system trust store only:", connect(client_context(), "localhost"))
print("lab CA, right hostname: ", connect(lab, "localhost"))
print("lab CA, wrong hostname: ", connect(lab, "rates.example"))python make_lab_certs.py
python test_fixed.py
python crypto_lint.py fixedwrote lab_ca.pem, server.pem, server.key (valid for one day)
same plaintext, different ciphertext: True
both decrypt: True
tampered message refused: InvalidTag
1000 tokens, all distinct: True | length: 43
system trust store only: refused: unable to get local issuer certificate
lab CA, right hostname: connected, TLSv1.3, got b'hello'
lab CA, wrong hostname: refused: Hostname mismatch
0 misuse findings
quantum-vulnerable public-key use (plan migration):Each line checks one promise. Two encryptions of the same text differ, so a fresh nonce is in use, and a single flipped bit is refused. A thousand distinct 43-character tokens rule out the crudest bugs, such as a constant token; a test cannot prove unpredictability, which is why the code relies on secrets. The three TLS lines matter most: the client refuses a certificate it has no reason to trust, accepts it once the right CA is supplied, and still refuses it for a name it does not cover. The old client_context() would have printed "connected" three times.
05. Step 4: plan the post-quantum migration
A large enough quantum computer running Shor's algorithm would break RSA and elliptic-curve cryptography (ECDH, ECDSA, X25519, Ed25519) at any practical key size. Symmetric algorithms are far less affected: NIST IR 8547 states that approved symmetric primitives with at least 128 bits of classical security are believed to meet its lowest post-quantum security category, so AES-256 and SHA-256 stay. Nobody knows when such a machine will exist, but one threat is already active: harvest now, decrypt later, where traffic recorded today is decrypted once the machine exists. Data that must stay secret for many years is therefore at risk now, through its key exchange.
NIST published the replacements in August 2024: ML-KEM (FIPS 203) for key establishment, and ML-DSA (FIPS 204) and SLH-DSA (FIPS 205) for signatures. The final NIST IR 8547 (October 2026) says quantum-vulnerable public-key algorithms will be deprecated after 2030 and disallowed in NIST standards after 2035. It also restates earlier deadlines from Executive Order 14412 and OMB M-26-15 for the most sensitive federal systems (2030 for key establishment, 2031 for signatures). It recommends ML-KEM-768 as the default parameter set. On the web, the transition has started with hybrid key exchange: RFC 10024 (August 2026) defines X25519MLKEM768 for TLS 1.3, which combines ML-KEM-768 with X25519 so that the session stays secure as long as either algorithm holds.
For this service, the inventory from step 2 turns into a plan:
- Key exchange first.
agree()and every TLS connection protect confidentiality, so they face harvest-now-decrypt-later. Upgrade TLS libraries and servers so that hybrid groups are offered, and plan a hybrid scheme foragree(). - Signatures second.
sign()protects authenticity, which an attacker can only break after the machine exists, so it can follow, unless signatures must stay valid for many years, as for firmware or long-term documents. - Crypto agility. Store an algorithm identifier and key id with every ciphertext and signature, and choose algorithms in configuration, so that the next change is a deployment rather than a rewrite.
- Keep the inventory alive. Run the scan in CI, and cover libraries, certificates and hardware too.
"""ML-KEM-768 (FIPS 203) with pyca/cryptography, and the hybrid idea used in TLS."""
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric.mlkem import MLKEM768PrivateKey
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
# Receiver publishes an encapsulation (public) key.
receiver = MLKEM768PrivateKey.generate()
public = receiver.public_key()
# Sender derives a shared secret plus a ciphertext that only the receiver can open.
sender_secret, ciphertext = public.encapsulate()
receiver_secret = receiver.decapsulate(ciphertext)
raw = public.public_bytes(Encoding.Raw, PublicFormat.Raw)
print("ML-KEM-768 public key bytes:", len(raw))
print("ciphertext bytes:", len(ciphertext))
print("shared secret bytes:", len(sender_secret))
print("both sides agree:", sender_secret == receiver_secret)
# Hybrid: combine with X25519 so the result is safe if EITHER part holds.
# RFC 10024 concatenates the ML-KEM secret, then the X25519 secret, and feeds
# the result into the TLS 1.3 key schedule; HKDF plays that role here.
a, b = X25519PrivateKey.generate(), X25519PrivateKey.generate()
classical = a.exchange(b.public_key())
key = HKDF(hashes.SHA256(), 32, salt=None, info=b"hybrid demo v1").derive(
sender_secret + classical)
print("hybrid session key bytes:", len(key))python pq_kem.pyML-KEM-768 public key bytes: 1184
ciphertext bytes: 1088
shared secret bytes: 32
both sides agree: True
hybrid session key bytes: 32A KEM, key encapsulation mechanism, works differently from Diffie-Hellman. The sender runs encapsulate on the receiver's public key and gets two things: a shared secret to keep and a ciphertext to send. Only the receiver's private key can decapsulate that ciphertext into the same secret. Migration is not free: an X25519 public key is 32 bytes, an ML-KEM-768 public key 1,184 bytes and its ciphertext 1,088 bytes, which affects handshakes and storage. The hybrid part of the script mirrors the idea of RFC 10024 in a few lines; in real systems use the hybrid groups your TLS library provides rather than combining secrets yourself.
06. Check your understanding
07. Apply it
Run crypto_lint.py against your file-encryption CLI and add one rule for a mistake you could imagine making in it, with a test file that triggers the rule. Then add an algorithm identifier and key id to the header of every encrypted file, and write a one-page migration note: which parts of the CLI use public-key cryptography today, which would move to ML-KEM or ML-DSA, and in what order.
08. Review prompt
From memory: list five kinds of cryptographic misuse from this lesson with one-line fixes. Then explain harvest-now-decrypt-later, name the NIST standards for post-quantum key establishment and signatures, and say why key exchange usually migrates before signatures.
References
- OWASP Cryptographic Storage Cheat Sheet
- Python docs: random (security warning)
- Python docs: ssl.create_default_context
- NIST Post-Quantum Cryptography Project
- NIST IR 8547: Transition to Post-Quantum Cryptography Standards
- FIPS 203: Module-Lattice-Based Key-Encapsulation Mechanism Standard
- RFC 10024: Post-Quantum Traditional Hybrid Key Agreement for TLS 1.3
- pyca/cryptography: ML-KEM
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.