The Cryptography Picture Book
Confidentiality Integrity Authenticity ✔Non-repudiation hide it · detect changes · prove who · can't deny it each goal has its own tool: encryption, hashes/MACs, signatures
PLATE 0 — Cryptography is a handful of building blocks that give you four guarantees.
A picture book for grown-ups · with commands and code

Cryptography, Without the Hand-Waving

Nine spreads: hashes, symmetric and public-key encryption, signatures, key exchange, certificates and TLS, password storage, and the mistakes that break real systems.

Say it like a pro

"AES-GCM or ChaCha20-Poly1305 for data, X25519 and Ed25519 for keys and signatures, Argon2id for passwords, TLS 1.3 on the wire, and never roll your own."

Use the tabs or the ← → keys. Use vetted libraries in real systems.

"hello" SHA-256 2cf24dba5fb0a30e…256 bits "hellp" SHA-256 7c5a9e0b13d4f8a6…totally different What a good hash gives you deterministic · fixed size · fast · tiny change → unrelated output pre-image resistance: can't recover the input from the hash collision resistance: can't find two inputs with the same hash Use for file integrity · deduplication · commit IDs · building blocks (HMAC, signatures) NOT for storing passwords on their own (too fast): see chapter 8
PLATE 1 — A fingerprint of data: easy to compute, impossible to reverse.
Chapter 1 · Hash functions & MACs

Fingerprints and tamper checks

$ echo -n "hello" | sha256sum
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824  -
$ echo -n "hellp" | sha256sum                        # one letter later: nothing alike
$ sha256sum ubuntu.iso ; sha256sum -c SHA256SUMS      # verify a download
$ echo -n "msg" | openssl dgst -sha256 -hmac "secretkey"   # HMAC: a hash with a key
$ openssl dgst -sha3-256 file.bin ; b2sum file.bin       # SHA-3, BLAKE2
import hashlib, hmac, secrets

h = hashlib.sha256(b"hello").hexdigest()

# HMAC: proves the message came from someone with the key and wasn't altered
key = secrets.token_bytes(32)
tag = hmac.new(key, b"amount=100&to=alice", hashlib.sha256).digest()
ok  = hmac.compare_digest(tag, hmac.new(key, received, hashlib.sha256).digest())   # constant-time compare!
AlgorithmStatus
MD5, SHA-1broken for collisions: don't use for security
SHA-256 / SHA-512, SHA-3good
BLAKE2 / BLAKE3fast and good
length extension
why you use HMAC, not hash(key + message)
Merkle tree
hash of hashes: efficient proofs of inclusion (git, blockchains, certificate transparency)
Say it like a pro

"SHA-256 for integrity, HMAC when a key is involved, and constant-time comparison for tags."

plaintext key (secret) nonce (unique) AES-256-GCMencrypt + authenticate ciphertext auth tag (16 B) Rules that matter more than the algorithm use authenticated encryption (AEAD): AES-GCM or ChaCha20-Poly1305 NEVER reuse a (key, nonce) pair: with GCM it leaks the key's secrets ECB mode leaks patterns (the "ECB penguin"); plain CBC without a MAC is malleable Key management is the hard part random keys from the OS CSPRNG · store in a KMS/HSM · rotate · never in source code
PLATE 2 — One shared secret, fast, and good for lots of data. Share the key safely.
Chapter 2 · Symmetric encryption

AES, ChaCha20, and authenticated modes

# pip install cryptography
import os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

key = AESGCM.generate_key(bit_length=256)          # keep this secret and safe
aes = AESGCM(key)

nonce = os.urandom(12)                              # 96-bit, unique per message
aad = b"user=42"                                    # authenticated but not encrypted (context)
ct = aes.encrypt(nonce, b"my secret note", aad)     # ciphertext + 16-byte tag
store = nonce + ct                                  # the nonce isn't secret; keep it with the ciphertext

pt = AESGCM(key).decrypt(store[:12], store[12:], aad)   # raises InvalidTag if tampered with
$ openssl rand -hex 32                            # a random 256-bit key
$ openssl enc -aes-256-cbc -pbkdf2 -salt -in a.txt -out a.enc   # password-based file encryption (quick use)
$ age -p -o a.age a.txt ; age -d a.age         # modern, simple file encryption
$ gpg -c a.txt                                 # passphrase encrypt (GnuPG)
block vs stream
AES works on 128-bit blocks; ChaCha20 is a stream cipher, fast on phones without AES hardware
key size
128-bit is enough; 256-bit gives extra margin (and quantum headroom)
envelope encryption
a data key encrypts the data; a master key in a KMS encrypts the data key
Say it like a pro

"AEAD with a fresh random nonce per message, keys from a KMS, and envelope encryption for bulk data."

Encrypt to Alice message Alice's PUBLICkey locks Alice's PRIVATEkey unlocks the public key can be posted anywhere; the private key never leaves Alice in practice: encrypt a random symmetric key (hybrid encryption), not the whole message Signatures run the other direction Alice's PRIVATEkey signs signature PUBLIC keyverifies proves it came from the private key holder, and wasn't altered algorithms: RSA (≥ 2048 bits), ECDSA, Ed25519 (modern default)
PLATE 3 — Two linked keys: what one does, only the other can undo.
Chapter 3 · Public-key cryptography

Key pairs, encryption, and signatures

$ openssl genpkey -algorithm ed25519 -out ed.key           # private key (guard it)
$ openssl pkey -in ed.key -pubout -out ed.pub               # public key (share it)
$ openssl pkeyutl -sign -inkey ed.key -rawin -in file.txt -out file.sig
$ openssl pkeyutl -verify -pubin -inkey ed.pub -rawin -in file.txt -sigfile file.sig
$ ssh-keygen -t ed25519 -C "me@laptop"                      # SSH uses the same idea
$ openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072 -out rsa.key
from cryptography.hazmat.primitives.asymmetric import ed25519

priv = ed25519.Ed25519PrivateKey.generate()
pub  = priv.public_key()
sig  = priv.sign(b"release-1.4.2.tar.gz sha256:ab12…")
pub.verify(sig, b"release-1.4.2.tar.gz sha256:ab12…")        # raises InvalidSignature if anything changed
AlgorithmUseNotes
Ed25519signaturessmall, fast, hard to misuse
ECDSA P-256signatures, TLSwidely supported
RSA 2048–4096signatures, encryptionlarge, slower; use OAEP/PSS padding
X25519key exchangenext chapter
quantum threat
Shor's algorithm would break RSA/ECC; NIST has standardized post-quantum schemes (ML-KEM, ML-DSA) and hybrids are rolling out
Say it like a pro

"Ed25519 for signatures, RSA only for compatibility with OAEP and PSS, and keys generated and held in a KMS."

public color Aliceprivate a Bobprivate b A = g^a (public) B = g^b (public) B^a = g^(ab) A^b = g^(ab) = same secret An eavesdropper sees g, A and B, but can't get g^(ab) ECDH (X25519) does the same with elliptic curves · ephemeral keys give forward secrecy
PLATE 4 — Two strangers agree on a secret in public, without ever sending it.
Chapter 4 · Key exchange & forward secrecy

Agreeing on a key over an open channel

Symmetric crypto is fast but needs a shared key. Diffie–Hellman lets two parties derive one over a public channel. Mixed with a signature (so you know who you're talking to), it's the heart of TLS, SSH, Signal and WireGuard.

from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.primitives import hashes

a = X25519PrivateKey.generate();  b = X25519PrivateKey.generate()
shared_a = a.exchange(b.public_key())             # Alice computes
shared_b = b.exchange(a.public_key())             # Bob computes
assert shared_a == shared_b

# never use the raw shared secret as a key: derive one with a KDF
key = HKDF(algorithm=hashes.SHA256(), length=32, salt=None, info=b"chat v1").derive(shared_a)
forward secrecy
new ephemeral keys per session, so stealing a long-term key later doesn't decrypt old recordings
man-in-the-middle
plain DH can't tell who it's talking to; signatures or certificates solve that
KDF
HKDF turns shared secrets into proper keys; Argon2/scrypt turn passwords into keys
$ wg genkey | tee private.key | wg pubkey > public.key     # WireGuard: X25519 under the hood
Say it like a pro

"Ephemeral X25519 for forward secrecy, authenticated by signatures, with keys derived through HKDF."

Client Server 1 ClientHello + key share 2 ServerHello + key share + certificate + signature 3 Finished → encrypted application data Chain of trust Root CA (in OS) Intermediate CA example.com the browser checks: signature chain · domain name matches · not expired · not revoked certificate transparency logs make rogue certificates visible One round trip, forward secrecy by default in TLS 1.3 old protocols (SSL, TLS 1.0/1.1) and weak ciphers are removed or disabled HSTS tells browsers "always use HTTPS for this site"
PLATE 5 — The padlock means "encrypted to someone a trusted authority says owns this name".
Chapter 5 · Certificates, PKI & TLS

How HTTPS actually works

$ openssl s_client -connect example.com:443 -servername example.com </dev/null 2>/dev/null | openssl x509 -noout -subject -issuer -dates -ext subjectAltName
$ openssl s_client -connect example.com:443 -tls1_3 -brief </dev/null      # protocol + cipher negotiated
$ curl -vI https://example.com 2>&1 | grep -E 'SSL|TLS|subject|issuer|expire'
$ echo | openssl s_client -connect example.com:443 -showcerts 2>/dev/null | grep -E '^ [0-9] s:'   # the chain

# your own CA for a lab (never for production trust)
$ openssl req -x509 -newkey ed25519 -nodes -keyout ca.key -out ca.crt -days 365 -subj "/CN=Lab CA"
$ openssl req -newkey ed25519 -nodes -keyout srv.key -out srv.csr -subj "/CN=app.test" -addext "subjectAltName=DNS:app.test"
$ openssl x509 -req -in srv.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out srv.crt -days 90 -copy_extensions copy
$ openssl verify -CAfile ca.crt srv.crt
$ sudo certbot --nginx -d example.com                       # free public cert via Let's Encrypt, auto-renew
CSR
certificate signing request: your public key + name, sent to a CA to sign
SAN
the names the cert is valid for (modern clients ignore the old CN)
mTLS
both sides present certificates: service-to-service identity
pinning / revocation
OCSP stapling and short-lived certs beat revocation lists in practice
Say it like a pro

"TLS 1.3 with automated short-lived certificates, HSTS, and mTLS between internal services."

✘ Math.random(), rand()predictable: fine for games,fatal for keys and tokens ✔ OS CSPRNG/dev/urandom · getrandom()secrets · crypto.randomBytes generate store use rotate destroy Where keys live best: HSM / cloud KMS (keys never leave; you ask it to encrypt or sign) good: secrets manager / Vault · OS keystore / Secure Enclave on phones bad: source code, env files in git, chat messages, shared drives back up keys (encrypted), or the data dies with them
PLATE 6 — Strong algorithms with weak randomness or sloppy key handling are no protection.
Chapter 6 · Randomness & key management

The unglamorous half of crypto

import secrets, os
token   = secrets.token_urlsafe(32)          # session IDs, reset tokens, API keys
key     = secrets.token_bytes(32)
code    = f"{secrets.randbelow(10**6):06d}"  # a 6-digit OTP, uniform
# ✘ random.random(), time-seeded RNGs, UUIDv1/v4 from weak sources as secrets
// Node / browser
import { randomBytes, randomUUID } from "node:crypto";
const t = randomBytes(32).toString("base64url");
const bytes = crypto.getRandomValues(new Uint8Array(32));        // Web Crypto in browsers
$ head -c 32 /dev/urandom | base64
$ openssl rand -base64 32
$ aws kms create-key --description "app data key" --key-usage ENCRYPT_DECRYPT
$ aws kms generate-data-key --key-id alias/app --key-spec AES_256       # envelope encryption
$ vault kv put secret/app api_key=…                                     # HashiCorp Vault
entropy
unpredictability, measured in bits. A random 128-bit key has 2¹²⁸ possibilities.
rotation
replace keys on a schedule and after any suspected exposure; design for it from day one
separation
different keys per purpose and per environment
Say it like a pro

"All secrets from the OS CSPRNG, keys in a KMS with rotation, and one key per purpose."

password random salt Argon2idslow + memory-hard $argon2id$m=65536,t=3,p=4$salt$hash Why not just SHA-256? a GPU tests billions of SHA-256 guesses per second · Argon2id makes each guess cost memory and time Rules unique random salt per password (defeats rainbow tables and shows duplicates) tune the cost to ~100–500 ms on your server · store the parameters in the hash string re-hash on login when parameters are upgraded · optional server-side "pepper" in a KMS order of preference: Argon2id → scrypt → bcrypt → PBKDF2 (if FIPS requires)
PLATE 7 — A password hash must be slow on purpose.
Chapter 7 · Passwords & key derivation

Store something an attacker can't cheaply reverse

# pip install argon2-cffi
from argon2 import PasswordHasher
ph = PasswordHasher(time_cost=3, memory_cost=64*1024, parallelism=4)   # tune to your hardware

stored = ph.hash("correct horse battery staple")      # includes salt + parameters
ph.verify(stored, "correct horse battery staple")      # True, or raises VerifyMismatchError
if ph.check_needs_rehash(stored): stored = ph.hash(plain_pw_at_login)
# deriving an encryption key from a passphrase (e.g. an encrypted vault file)
import hashlib, os
salt = os.urandom(16)
key = hashlib.scrypt(b"passphrase", salt=salt, n=2**15, r=8, p=1, dklen=32, maxmem=2**26)
$ python -c "import bcrypt;print(bcrypt.hashpw(b'pw', bcrypt.gensalt(12)))"      # bcrypt alternative
$ hashcat -m 0 -a 0 hashes.txt rockyou.txt                                # audit YOUR OWN hashes: how fast would an attacker be?
passkeys
public-key login (WebAuthn) removes shared secrets entirely: nothing to leak from your database
HaveIBeenPwned
k-anonymity API lets you reject known-breached passwords without sending the password
Say it like a pro

"Argon2id with a unique salt, tuned cost, rehash on login, and breached-password checks at signup."

✘ invented algorithm / "obfuscation" → ✔ vetted libraries (libsodium, cryptography) ✘ AES-ECB or CBC without a MAC → ✔ AES-GCM / ChaCha20-Poly1305 ✘ reusing a nonce / IV with the same key → ✔ fresh random or counter nonce ✘ keys in source, images, or client apps → ✔ KMS / secrets manager ✘ Math.random() for tokens → ✔ CSPRNG (secrets, randomBytes) ✘ == to compare MACs/tokens (timing leak) → ✔ constant-time compare ✘ verify=False / skipping cert checks → ✔ fix the trust chain instead "Anyone can invent a cipher they can't break themselves." — Schneier's law
PLATE 8 — Real systems fail at the edges of the crypto, not in the mathematics.
Chapter 8 · Common mistakes & attacks

How strong crypto still gets broken

padding oracle
error messages reveal whether padding was valid, letting attackers decrypt CBC data; AEAD fixes it
timing attack
early-exit comparisons leak how many bytes matched; use hmac.compare_digest
downgrade
forcing old protocol versions; disable them server-side
side channels
power, cache, and speculative-execution leaks; use constant-time, audited libraries
replay
re-sending a valid message; add nonces, timestamps and expiry
CBOM / agility
inventory what crypto you use so you can swap algorithms (post-quantum) later
# audit your own server's TLS configuration
$ nmap --script ssl-enum-ciphers -p 443 yourdomain.example
$ testssl.sh yourdomain.example                         # comprehensive TLS check
$ sslyze yourdomain.example
# search your own code for crypto smells
$ grep -rnE "MD5|SHA1|ECB|Math\.random|verify=False|DES" src/
$ semgrep --config p/security-audit .
Say it like a pro

"AEAD, constant-time comparisons, no downgrade paths, and scans in CI for weak algorithms and disabled verification."

Alice relay serversees ciphertext only Bob A tiny end-to-end design, step by step 1 · each user has a long-term Ed25519 identity key (signs) + X25519 key (agrees) 2 · Alice derives a shared key with Bob's X25519 public key (HKDF) 3 · encrypt with ChaCha20-Poly1305, fresh nonce, bind sender/recipient in the AAD 4 · sign the ciphertext with her identity key · 5 · Bob verifies, then decrypts Missing for real use verifying identity keys (safety numbers) · ratcheting for forward secrecy key transparency · metadata · groups: use Signal Protocol / MLS, don't DIY
PLATE 9 — Building blocks compose into protocols. Use proven protocols for the real thing.
Chapter 9 · Putting it together

A small sealed-message demo

from cryptography.hazmat.primitives.asymmetric import x25519, ed25519
from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.primitives import hashes
import os

def derive(shared): return HKDF(hashes.SHA256(), 32, None, b"demo-msg-v1").derive(shared)

# long-term keys
alice_x, bob_x = x25519.X25519PrivateKey.generate(), x25519.X25519PrivateKey.generate()
alice_sig = ed25519.Ed25519PrivateKey.generate()

# Alice → Bob
key = derive(alice_x.exchange(bob_x.public_key()))
nonce = os.urandom(12)
aad = b"alice->bob"
ct = ChaCha20Poly1305(key).encrypt(nonce, b"meet at 6", aad)
sig = alice_sig.sign(nonce + ct + aad)

# Bob verifies first, then decrypts
alice_sig.public_key().verify(sig, nonce + ct + aad)
pt = ChaCha20Poly1305(derive(bob_x.exchange(alice_x.public_key()))).decrypt(nonce, ct, aad)
print(pt)      # b'meet at 6'
  1. Choose a protocol, not primitives: TLS, SSH, Noise, Signal, age, or libsodium's high-level API.
  2. Pick modern defaults: X25519, Ed25519, ChaCha20-Poly1305 / AES-GCM, SHA-256, Argon2id.
  3. Manage keys properly: KMS, rotation, backups, least privilege.
  4. Test and review: known-answer tests, audits, and threat modeling.
practise
Cryptopals challenges · CryptoHack · the "Crypto 101" book (free) · libsodium docs
read next
"Serious Cryptography" (Aumasson) · "Real-World Cryptography" (Wong) · "Applied Cryptography" (Schneier)
Say it like a pro

"I use a proven protocol with modern defaults, keep keys in a KMS, and never design primitives myself."