Chapter 4Applied cryptography
In 2010 a group of researchers recovered the private key Sony used to sign PlayStation 3 software, because Sony's ECDSA code used the same "random" number for every signature. The elliptic curve math was sound; one constant where a fresh secret belonged gave away the key that protected the whole platform. This chapter teaches the primitives you will actually use, how they fit together in TLS, and the specific mistakes that break them in production.
After this chapter you can
- Choose the right primitive for a job: hash, MAC, password hash, AEAD cipher, key exchange or signature
- Explain why passwords need slow, salted, memory-hard hashing and pick parameters
- Describe how certificates chain to a trusted root and what a client checks
- Walk through the TLS 1.3 handshake message by message and say what each one proves
- Recognize nonce reuse, ECB mode, homemade schemes and bad randomness in real code
- Explain the state of post-quantum migration and what to do about it now
Hashes, MACs and password hashing
A cryptographic hash function maps any input to a fixed-size digest, such as 256 bits for SHA-256. It must be one-way (you cannot find an input for a given digest), second-preimage resistant (you cannot find a different input with the same digest as a given one) and collision resistant (you cannot find any two inputs with the same digest). Change one bit of input and about half the output bits flip.
printf 'hello' | openssl dgst -sha256
printf 'hellp' | openssl dgst -sha256 # completely different digest| Algorithm | Status | Use it for |
|---|---|---|
| MD5 | Broken: collisions in seconds | Nothing security related |
| SHA-1 | Broken: practical collision shown in 2017 (SHAttered) | Legacy only, migrate away |
| SHA-256, SHA-512 (SHA-2) | Secure | Default choice: integrity, signatures, HMAC |
| SHA-3, BLAKE2, BLAKE3 | Secure | Alternatives, BLAKE family is very fast |
A hash alone proves nothing about who produced data, because anyone can compute it. A MAC (message authentication code) mixes in a secret key, so only key holders can produce a valid tag. Use HMAC: the naive SHA256(key + message) is vulnerable to length extension with SHA-2, which lets an attacker append data and compute a valid tag without the key. Always compare tags with a constant-time function such as hmac.compare_digest, because an ordinary == returns early and leaks how many bytes matched.
Passwords need a different kind of hash
Fast hashes are wrong for passwords. A single modern GPU computes billions of SHA-256 hashes per second, so a leaked table of unsalted SHA-256 password hashes falls to dictionary attacks in hours. Password hashing functions are deliberately slow and, ideally, memory-hard, so that each guess costs real RAM and defeats GPU parallelism.
| Function | Recommended starting parameters (OWASP) | Notes |
|---|---|---|
| Argon2id | 19 MiB memory, 2 iterations, 1 lane | First choice for new systems |
| scrypt | N = 2^17, r = 8, p = 1 | Memory-hard, good if Argon2 is unavailable |
| bcrypt | Cost 10 or higher | Widely available, truncates input at 72 bytes |
| PBKDF2-HMAC-SHA256 | 600,000 iterations | Use when FIPS compliance requires it |
Every password gets a unique random salt, stored next to the hash, so identical passwords produce different hashes and precomputed tables are useless. The goal is making each guess expensive for attackers while a single login stays fast enough for users, typically well under a second.
Symmetric encryption and AEAD
Symmetric encryption uses one shared key to encrypt and decrypt. AES is the standard block cipher: it transforms 16-byte blocks under a 128 or 256-bit key, and modern CPUs have dedicated instructions for it. A block cipher alone only handles one block, so a mode of operation defines how to encrypt longer messages, and the mode is where most mistakes happen.
Encryption without integrity is dangerous. An attacker who flips bits in ciphertext can often flip predictable bits in plaintext, or use error messages as an oracle to decrypt (the padding oracle attacks against CBC mode). Modern designs therefore use AEAD (authenticated encryption with associated data), which encrypts and authenticates in one operation.
| Construction | Strengths | Watch out for |
|---|---|---|
| AES-256-GCM | Very fast with AES hardware, the TLS default | 96-bit nonce must never repeat under one key |
| ChaCha20-Poly1305 | Fast in software, constant time without special hardware | Same nonce rule |
| XChaCha20-Poly1305 | 192-bit nonce, safe to choose randomly | Not in every library |
| AES-ECB | None | Leaks patterns, never use |
| AES-CBC without a MAC | None worth having | Padding oracles, malleability |
Associated data is information that must not be tampered with but need not be secret, such as a record ID or header. Binding it into the tag stops an attacker from moving a valid ciphertext into a different context, for example swapping the encrypted balance of one account into another row.
Public-key cryptography: key exchange and signatures
Symmetric crypto needs a shared key, which raises the question of how two strangers agree on one over a network that attackers can read. Asymmetric cryptography answers it with key pairs: a public key you can publish and a private key you never share. It gives you two distinct tools: key exchange and digital signatures.
Key exchange (Diffie-Hellman, today almost always the elliptic curve version, ECDH, often over Curve25519 as X25519) lets each side combine its own private key with the other's public key and arrive at the same shared secret. An eavesdropper who sees both public keys cannot compute it.
When both sides generate fresh key pairs for every session and delete them afterwards, you get forward secrecy: stealing a server's long-term key later does not decrypt recorded past sessions. TLS 1.3 requires this.
Digital signatures use the private key to sign and the public key to verify. They prove who produced data (authenticity), that it was not changed (integrity), and they support non-repudiation because only the key holder could have signed. Note that key exchange alone does not tell you who is on the other side, which is why TLS combines it with a signature from a certified key.
| Algorithm | Type | Notes |
|---|---|---|
| RSA-2048 or larger | Signatures, legacy encryption | Large keys, slow key generation. Use PSS for signatures, OAEP for encryption |
| ECDSA P-256 | Signatures | Needs a unique secret nonce per signature, as Sony learned |
| Ed25519 | Signatures | Deterministic nonces by design, hard to misuse, a strong default |
| X25519, ECDH P-256 | Key exchange | Used in TLS, SSH, Signal and WireGuard |
Certificates and PKI
A public key is just a number. To trust that a key belongs to bank.example, you need someone you already trust to vouch for it. A certificate is a signed statement binding a public key to a name, with a validity period and usage constraints. PKI (public key infrastructure) is the system of certificate authorities (CAs), policies and trust stores that issue and check these statements.
When your browser receives a chain, it checks several things:
- Each signature in the chain verifies with the issuer's public key, ending at a root in the local trust store.
- The current time is inside each certificate's validity period.
- The leaf's Subject Alternative Name matches the hostname you requested.
- Constraints hold: only CA certificates may sign others, and the leaf allows server authentication.
- The certificate appears in Certificate Transparency logs, public append-only logs that let domain owners spot certificates issued for their names without permission.
Revocation has always been weak: browsers rarely block on online checks. The industry's answer is short lifetimes. Under a CA/Browser Forum ballot passed in 2025, the maximum lifetime of public TLS certificates dropped to 200 days in March 2026, falls to 100 days in March 2027 and to 47 days in March 2029, which makes automated renewal (ACME, as used by Let's Encrypt) effectively mandatory.
The TLS 1.3 handshake
TLS 1.3 (RFC 8446) combines everything above into one protocol. It completes in one round trip and encrypts everything after the ServerHello, including the certificate.
ClientHello
The client sends a random value, the AEAD cipher suites it supports, the signature algorithms it accepts, the server name, and a key share for its preferred group, guessing in advance to save a round trip.
ServerHello
The server picks a cipher suite and group and returns its own key share. Both sides now compute the same shared secret and run it through HKDF to derive handshake traffic keys. From here on everything is encrypted.
Certificate and CertificateVerify
The server sends its certificate chain, then signs a hash of every handshake message so far with the certificate's private key. This proves it holds that key and binds the signature to this specific key exchange, which defeats an on-path attacker who substituted key shares.
Finished
Each side sends a MAC over the whole transcript under a key derived from the handshake secret. If any message was altered or downgraded, the MACs do not match and the connection aborts.
TLS 1.3 also deleted most of what went wrong in earlier versions: RSA key transport (no forward secrecy), CBC and RC4 ciphers, compression and renegotiation are gone, leaving five AEAD-only cipher suites. The one sharp edge it added is optional 0-RTT data, which an attacker can replay, so servers should only accept it for idempotent requests.
How cryptography fails in practice
Real crypto failures almost never come from someone breaking AES. They come from misuse of correct primitives, and the same handful recur.
| Failure | What goes wrong | Real example | Fix |
|---|---|---|---|
| Nonce reuse | Two messages under one key and nonce leak the XOR of plaintexts, and GCM's authentication key can be recovered | ECDSA nonce reuse exposed Sony's PS3 signing key | Counters or random 192-bit nonces (XChaCha), or misuse-resistant AES-GCM-SIV |
| ECB mode | Identical plaintext blocks give identical ciphertext blocks | The famous ECB penguin image, still visible when encrypted | Use an AEAD mode |
| Bad randomness | Keys become guessable | Debian's 2006 to 2008 OpenSSL patch left only the process ID as entropy, so about 32,768 possible keys per type (CVE-2008-0166) | Use the OS CSPRNG: os.urandom, secrets, getrandom() |
| Rolling your own | Homemade schemes lack years of analysis | Custom XOR or home-made token formats broken in hours | Use high-level vetted libraries |
| Timing leaks | Comparisons or operations that take data-dependent time | Early-exit tag comparison | Constant-time comparisons and libraries |
| Unauthenticated encryption | Attacker modifies ciphertext or uses error oracles | CBC padding oracles | AEAD, verify before using any plaintext |
The pattern behind most of these is that APIs that allow misuse get misused. Prefer libraries with high-level interfaces that choose safe defaults, such as libsodium or the recipes layer of Python's cryptography package, over assembling raw primitives yourself.
Post-quantum migration
A large enough quantum computer running Shor's algorithm would break RSA, finite-field Diffie-Hellman and elliptic curve crypto. Symmetric ciphers and hashes are affected far less: Grover's algorithm at most halves effective key strength, so AES-256 and SHA-256 remain fine. Nobody can date when such a machine will exist, but harvest now, decrypt later is a present threat: traffic recorded today can be decrypted once one does.
| Standard | Algorithm | Replaces | Status as of late 2026 |
|---|---|---|---|
| FIPS 203 | ML-KEM (from Kyber) | ECDH and RSA key exchange | Final since August 2024 |
| FIPS 204 | ML-DSA (from Dilithium) | RSA and ECDSA signatures | Final since August 2024 |
| FIPS 205 | SLH-DSA (from SPHINCS+) | Signatures, conservative hash-based backup | Final since August 2024 |
| FIPS 206 | FN-DSA (from Falcon) | Compact signatures | In draft, not yet final |
| Planned | HQC | Backup KEM based on different math | Selected March 2025, final standard expected around 2027 |
Key exchange has moved first, because it protects against recording now. Major browsers and OpenSSL 3.5 and later offer the hybrid group X25519MLKEM768 by default, which combines classical X25519 with ML-KEM-768 so the session stays safe if either one is broken. You saw that group in the handshake diagram, and you will see it negotiated in the lab.
Signatures and certificates are slower to move, because post-quantum signatures are much larger (an ML-DSA-44 signature is 2,420 bytes against 64 bytes for Ed25519) and every certificate chain carries several. NIST's draft transition guidance (IR 8547) proposes deprecating today's public-key algorithms after 2030 and disallowing them after 2035. The practical work now is an inventory: find where your systems use RSA and elliptic curves, especially long-lived data and keys, and make algorithms configurable rather than hard-coded.
Key terms
- Hash function
- A one-way function that maps any input to a fixed-size digest, where collisions are infeasible to find.
- HMAC
- A construction that turns a hash function and a secret key into a message authentication code.
- Salt
- A unique random value stored with each password hash so identical passwords hash differently.
- AEAD
- Authenticated encryption with associated data: encryption that also detects any modification of ciphertext or bound metadata.
- Nonce
- A number used once per key; repeating it under the same key breaks stream-based AEAD ciphers.
- Forward secrecy
- The property that compromising a long-term key does not expose past session keys, achieved with ephemeral key exchange.
- Digital signature
- A value produced with a private key that anyone can verify with the public key, proving origin and integrity.
- Certificate
- A CA-signed statement binding a public key to a name, with validity dates and usage constraints.
- Certificate Transparency
- Public append-only logs of issued certificates that let anyone detect misissuance.
- ML-KEM
- The NIST post-quantum key encapsulation standard (FIPS 203), used in hybrid TLS key exchange.
Build a private PKI and inspect a TLS 1.3 handshake with openssl
Goal: create your own root CA, issue a server certificate, verify the chain, sign a file, and watch a TLS 1.3 handshake negotiate a post-quantum hybrid group on your own machine.
You need: OpenSSL 3.5 or newer (check with openssl version; on macOS run brew install openssl@3 because the system openssl is LibreSSL; Debian 13 and Ubuntu 25.10 or later package a new enough version; otherwise use docker run --rm -it alpine:3.22 sh and apk add openssl). Everything runs on localhost.
-
Hash and MAC a file:
mkdir pki-lab && cd pki-lab echo "hello" > msg.txt openssl dgst -sha256 msg.txt openssl dgst -sha256 -hmac 'secret-key' msg.txtThe two digests differ, and the HMAC changes completely if you change the key.
-
Create a root CA with an Ed25519 key:
openssl genpkey -algorithm ed25519 -out ca.key openssl req -x509 -new -key ca.key -subj "/CN=Lab Root CA" -days 30 -out ca.crt \ -addext "basicConstraints=critical,CA:TRUE" \ -addext "keyUsage=critical,keyCertSign,cRLSign" -
Create a server key and certificate signing request, then issue the certificate:
openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out server.key openssl req -new -key server.key -subj "/CN=localhost" -out server.csr printf "subjectAltName=DNS:localhost\nbasicConstraints=CA:FALSE\nextendedKeyUsage=serverAuth\n" > ext.cnf openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial \ -days 7 -extfile ext.cnf -out server.crt openssl verify -CAfile ca.crt server.crtExpect
server.crt: OK. Runopenssl x509 -in server.crt -noout -textand find the issuer, validity dates and Subject Alternative Name. -
Sign and verify a file with the CA key, then tamper with it:
openssl pkey -in ca.key -pubout -out ca.pub openssl pkeyutl -sign -inkey ca.key -rawin -in msg.txt -out msg.sig openssl pkeyutl -verify -pubin -inkey ca.pub -rawin -in msg.txt -sigfile msg.sig echo "tampered" >> msg.txt openssl pkeyutl -verify -pubin -inkey ca.pub -rawin -in msg.txt -sigfile msg.sigExpect
Signature Verified Successfully, then a verification failure after tampering. -
Start a TLS server in one terminal and connect from another:
openssl s_server -accept 8443 -cert server.crt -key server.key -wwwecho | openssl s_client -connect localhost:8443 -CAfile ca.crt -servername localhost -msgIn the output, find ClientHello, ServerHello, EncryptedExtensions, Certificate, CertificateVerify and Finished in order. Near the end you should see
Negotiated TLS1.3 group: X25519MLKEM768,Protocol: TLSv1.3andVerify return code: 0 (ok). -
Break verification on purpose: connect with
-servername wrong.example -verify_hostname wrong.exampleand note the hostname mismatch error. Then connect without-CAfileand note that the chain is untrusted.
Check your work: you can show a verified chain, a signature that fails after tampering, and a handshake transcript with the six TLS 1.3 handshake messages and the hybrid post-quantum group.
Stretch: force a classical group with -groups X25519 on the client and compare the ClientHello length with the default (the ML-KEM share adds over a kilobyte). Then capture the handshake in Wireshark on the loopback interface and confirm the certificate is not visible in plaintext.
Break and fix encryption with Python cryptography
Goal: see AEAD reject tampering, recover a plaintext from nonce reuse without the key, and measure why password hashing must be slow.
You need: Python 3.10 or newer and the cryptography package (Argon2id needs version 44 or later):
python3 -m venv .venv && source .venv/bin/activate
pip install cryptography-
Save this as
aead.pyand run it:aead.py import os from cryptography.hazmat.primitives.ciphers.aead import AESGCM from cryptography.exceptions import InvalidTag key = AESGCM.generate_key(bit_length=256) aead = AESGCM(key) nonce = os.urandom(12) aad = b"order-id=1042" ct = aead.encrypt(nonce, b"amount=10.00 EUR", aad) print("decrypted:", aead.decrypt(nonce, ct, aad)) tampered = bytearray(ct) tampered[7] ^= 0x01 try: aead.decrypt(nonce, bytes(tampered), aad) except InvalidTag: print("tampering detected") try: aead.decrypt(nonce, ct, b"order-id=9999") except InvalidTag: print("wrong associated data detected")Expect the plaintext, then both rejections. Flipping one bit or changing the order ID makes decryption fail with no output.
-
Save this as
nonce_reuse.pyand run it:nonce_reuse.py import os from cryptography.hazmat.primitives.ciphers.aead import AESGCM aead = AESGCM(AESGCM.generate_key(bit_length=256)) nonce = os.urandom(12) # the bug: reused below p1 = b"transfer 100 to alice" p2 = b"transfer 999 to mallo" c1 = aead.encrypt(nonce, p1, None)[:-16] # strip the 16-byte tag c2 = aead.encrypt(nonce, p2, None)[:-16] xor = bytes(a ^ b for a, b in zip(c1, c2)) recovered = bytes(a ^ b for a, b in zip(xor, p1)) print("recovered without the key:", recovered)Expect
recovered without the key: b'transfer 999 to mallo'. GCM is a stream construction, so the same key and nonce produce the same keystream, and knowing one plaintext reveals the other. -
Fix it: generate a new nonce for each call, rerun, and confirm the recovered bytes are now garbage.
-
Save this as
passwords.pyand run it:passwords.py import os, time, hashlib from cryptography.hazmat.primitives.kdf.argon2 import Argon2id password = b"correct horse battery staple" start = time.perf_counter() for _ in range(100_000): hashlib.sha256(password).digest() print("SHA-256 guesses per second:", round(100_000 / (time.perf_counter() - start))) salt = os.urandom(16) start = time.perf_counter() digest = Argon2id(salt=salt, length=32, iterations=2, lanes=1, memory_cost=19 * 1024).derive(password) print("Argon2id guesses per second:", round(1 / (time.perf_counter() - start), 1))On a laptop expect hundreds of thousands of SHA-256 guesses per second from plain Python (a GPU does billions) against a few dozen Argon2id guesses, each needing 19 MiB of memory.
Check your work: your terminal shows two InvalidTag rejections, a plaintext recovered from nonce reuse, and a gap of four or more orders of magnitude between SHA-256 and Argon2id speed.
Stretch: rewrite nonce_reuse.py with AESGCMSIV from the same module and show that reusing a nonce now only reveals whether two plaintexts are identical, then put all three scripts in a repo with a README explaining each failure.
Check yourself
A developer stores passwords as SHA-256 of the password plus a per-user random salt. What is the main remaining weakness?
A service encrypts records with AES-GCM using a fixed key and a nonce taken from a counter that resets to zero whenever the service restarts. What happens?
In the TLS 1.3 handshake, what does the CertificateVerify message prove that the Certificate message alone does not?
An attacker records encrypted TLS 1.3 traffic today and steals the server's certificate private key next year. Using a classical-only key exchange, what can they decrypt?
Why are browsers deploying hybrid X25519MLKEM768 rather than ML-KEM alone?
Recap
- Pick the primitive by job: hash for integrity, HMAC for authenticity with a shared key, Argon2id for passwords, AEAD for encryption.
- AEAD ciphers are safe only while every nonce is unique per key.
- Key exchange creates shared secrets, signatures prove identity, and TLS needs both.
- Certificates chain to a trusted root, and shrinking lifetimes make automated renewal mandatory.
- Real crypto breaks through misuse: nonce reuse, ECB, bad randomness and homemade schemes.
- Post-quantum key exchange is already deployed as a hybrid; start inventorying signatures and long-lived keys.
Go deeper
- pyca/cryptography documentation: the library used in the lab, with safe high-level recipes.
- OWASP Password Storage Cheat Sheet: current parameters for Argon2id, scrypt, bcrypt and PBKDF2.
- RFC 8446: TLS 1.3: the specification, readable once you know the handshake shape.
- The Illustrated TLS 1.3 Connection: every byte of a real handshake, annotated.
- NIST Post-Quantum Cryptography project: authoritative status of the PQC standards.
- Cryptopals challenges: hands-on exercises that have you break real crypto misuse yourself.