Cryptography §
Cryptography provides mathematical tools to protect data from adversaries: encryption (confidentiality), authentication (integrity), and key exchange (agreement). It is relevant whenever data must be kept secret, verified, or agreed upon between parties who do not share a pre-existing secret.
How these pieces fit together §
Modern cryptography is a tower of constructions: each layer assumes only the one below it. Randomness seeds a PRF/PRG, which turns a short key into an unlimited-looking keystream; a block or stream cipher uses that to encrypt; an AEAD wraps the cipher with authentication; a KDF derives the keys from a shared secret; and key exchange (Diffie–Hellman or a KEM) establishes that shared secret between strangers. Hybrid encryption (what TLS does) is simply the whole stack assembled end to end.
Security parameter. Modern cryptography is parameterized by a security level (e.g., bits). A scheme is secure if no adversary running in time can break it with non-negligible probability. Key sizes map to security levels (NIST SP 800-57): AES-128 → 128-bit classical / 64-bit quantum (Grover’s algorithm quadratically speeds up brute force, halving the exponent), AES-256 → 256-bit classical / 128-bit quantum, RSA-2048 → 112-bit, RSA-3072 → 128-bit, EC-256 → 128-bit.
Authoritative sources
- New Directions in Cryptography (Diffie & Hellman, 1976)
- The Design of Rijndael: AES (Daemen & Rijmen)
- NIST SP 800-57 Part 1 Rev 5: Recommendation for Key Management
- NIST SP 800-38A: Recommendation for Block Cipher Modes of Operation
- RFC 2898: PBKDF2
- FIPS 203: Module-Lattice-Based Key-Encapsulation Mechanism (ML-KEM)
Randomness §
A PRNG (Pseudo-Random Number Generator) is a deterministic function that, given a secret seed (state) , produces a sequence indistinguishable from uniform to any efficient observer. The state is the internal memory; the cycle is the period before the sequence repeats. A random oracle is an idealized function that returns a uniform random value for each new input and is consistent on repeated inputs.
Details
Step 1 — The global picture. A PRNG is a state machine: seed the state once, then each call updates the state and emits a function of it. Security means next-output unpredictability: an adversary who has seen any number of outputs must be unable to predict the next one. This divides PRNGs into two families: statistical PRNGs (LCG, Mersenne Twister), which look uniform but are predictable, and CSPRNGs (ChaCha20, AES-CTR-DRBG), which are unpredictable because recovering the state from the outputs is computationally infeasible.
Step 2 — A concrete example. Take an LCG with , , , seed . The outputs are 7, 10, 5, 9, 11, 12, 6, 3, 8, 4, 2, then back to 1: the cycle has length 12. Knowing the parameters and a single output, an attacker computes every past and future value with simple arithmetic — the sequence only looks random. A CSPRNG with a 256-bit state behaves the same way internally, but the state update is a cryptographic function, so recovering the state from outputs costs about operations.
Step 3 — Authoritative sources. The standard for random bit generation is NIST SP 800-90A: Recommendation for Random Bit Generation.
Step 4 — Example problem.
Example problem: why an LCG must never guard a secret
A lottery site draws numbers with an LCG where , , , and publishes each draw. An attacker sees two consecutive outputs. Explain how they predict all future draws.
Solution
The current state is the last output. Solve for it: . Since is odd, it is invertible modulo (odd numbers share no factor with ), so the inverse exists and is computable with the extended Euclidean algorithm. With recovered, the attacker replays the recurrence forward and knows every future draw before it happens. The fix is a CSPRNG, where the state update is a one-way function of the state (see the one-way functions in the Asymmetric cryptography section).
Block and stream ciphers §
A one-time pad (OTP) encrypts with a uniform random key of the same length: . It is information-theoretically secure (Shannon, 1949) but requires a key as long as the message. The security rests on the entropy of the key: if bits, the ciphertext is independent of the plaintext (see Coding and entropy for the entropy definitions). The OTP is the only cipher with unconditional security; all practical ciphers rely on computational assumptions.
A PRF (Pseudo-Random Function) is a keyed function indistinguishable from a uniform random function to any efficient adversary. A PRP (Pseudo-Random Permutation) is a keyed bijection indistinguishable from a uniform random permutation.
Stream cipher: encrypts a keystream (from a PRF) XORed with the plaintext. CTR mode turns a block cipher into a stream cipher: . The nonce must be unique per message (reusing a nonce with the same key breaks security).
Block cipher modes:
- ECB (Electronic Codebook): encrypt each block independently. Insecure: identical plaintext blocks produce identical ciphertext blocks.
- CBC (Cipher Block Chaining): with . The IV (initialization vector) must be random and unique.
IND-CPA (Indistinguishability under Chosen-Plaintext Attack): the adversary chooses two messages and receives the encryption of one; it must not distinguish which. CBC and CTR achieve IND-CPA.
IND-CCA (Indistinguishability under Chosen-Ciphertext Attack): the adversary can also query a decryption oracle. Requires an AEAD (Authenticated Encryption with Associated Data) scheme — see Authentication and hashing below.
Details
Step 1 — The global picture. Practical ciphers are built by climbing from the OTP: a PRG (PRF on a counter) stretches a short seed into a long keystream, giving a stream cipher; a PRP on fixed-size blocks gives a block cipher, and modes of operation chain the blocks. The security ladder goes: OTP (unconditional) → IND-CPA (safe against eavesdroppers) → IND-CCA (safe against active tampering, needs authentication).
Step 2 — A concrete example: ECB leaks patterns. Encrypt the two-block message . ECB applies to each block independently, so : the repetition in the plaintext is copied to the ciphertext. CBC mixes each block with the previous ciphertext (or the IV) before encrypting, so identical plaintext blocks produce different ciphertext blocks. CTR encrypts a counter to make a keystream, so no plaintext block ever meets directly.
You can reproduce all three modes interactively in the Interactive exploration section at the end of this page.
Step 3 — Building a block cipher: the Feistel network. A Feistel round splits the block into halves and computes , . The magic: because only the output is XORed, the round is invertible even if is not — decryption runs the same rounds with reversed key order. Luby–Rackoff (1986) proved that 3 rounds turn a PRF into a PRP (IND-CPA secure) and 4 rounds into a strong PRP (IND-CCA secure).
Step 4 — AES and cryptanalysis. AES (Rijndael): 128-bit block, 128/192/256-bit key, 10/12/14 rounds. Each round: SubBytes (S-box), ShiftRows, MixColumns, AddRoundKey. The S-box is a nonlinear permutation over (the finite field with 256 elements, built over ). AES implements Shannon’s two principles: diffusion spreads the influence of one plaintext bit across many ciphertext bits; confusion makes the key–ciphertext relationship complex. The two generic attacks on such designs are linear cryptanalysis (Matsui, 1993: find linear approximations holding with probability away from 1/2, recover key bits) and differential cryptanalysis (Biham & Shamir, 1990: find input differences predicting output differences, recover key bits). AES’s round count is chosen so both attacks cost more than brute force.
Step 5 — Authoritative sources. The modes above are specified in NIST SP 800-38A, and AES in FIPS 197; the Feistel result is Luby & Rackoff, “How to Construct Pseudorandom Permutations from Pseudorandom Functions” (1988).
Step 6 — Example problem.
Example problem: nonce reuse in CTR mode
An encryptor reuses the same nonce for two messages and under the same CTR key. Show what an eavesdropper learns, and why this reduces the scheme to a two-time pad.
Solution
CTR computes and — the same keystream for both. XORing the ciphertexts cancels the keystream: . The eavesdropper now holds the XOR of two plaintexts, exactly the situation of a two-time pad: if has known structure (headers, padding, natural language), can often be recovered by crib-dragging. Uniqueness of the nonce per key is therefore a hard requirement, not a recommendation.
Authentication and hashing §
A hash is collision-resistant and preimage-resistant: it fingerprints data without any key. A MAC (Message Authentication Code) is a keyed hash: only holders of can produce a valid tag, so a valid tag authenticates both the message and its origin. An AEAD (Authenticated Encryption with Associated Data, e.g., AES-GCM, ChaCha20-Poly1305) combines encryption and authentication in one primitive, achieving IND-CCA security.
Details
Step 1 — The global picture. Three tools, three questions: has this data changed? (hash), did someone with the key vouch for this data? (MAC), is this ciphertext both secret and vouched for? (AEAD). When composing encryption and a MAC by hand, order matters: EtM (Encrypt-then-MAC) is the only composition provably secure in general (given a CPA-secure encryption and a secure MAC; Bellare & Namprempre, 2000). MtE (MAC-then-Encrypt) and E&M (Encrypt-and-MAC) are not provably secure in general — MtE’s flaws led to real padding-oracle attacks (e.g., Lucky 13 on TLS).
Step 2 — A concrete example. To authenticate with HMAC: compute — the two pads make the construction a secure MAC even though plain is not. To encrypt and authenticate with GCM: run CTR mode for confidentiality, then compute a Galois-field MAC (GHASH) over the ciphertext and associated data; the tag covers both, so headers can be authenticated without being encrypted.
Step 3 — The sponge construction. SHA-3 (Keccak) is built as a sponge: a permutation on bits; absorb the message into the state block by block, then squeeze out the output. The rate is the part of the state touched per block; the capacity is the untouched part. Security: preimage resistance up to bits, and collision resistance up to bits. For example, SHAKE128 has rate 1344 and capacity 256, giving 128 bits of preimage security (), independent of the large rate.
Step 4 — Modern AEAD properties. Key-committing AEAD: the ciphertext commits to the key (no different key decrypts it to the same plaintext) — important when the decrypted plaintext is fed to another key-dependent component. Misuse-resistant AEAD (e.g., SIV mode): remains secure even if the nonce is accidentally reused, at the cost of two passes over the data.
Step 5 — Authoritative sources. FIPS 202: SHA-3 Standard, RFC 8439: ChaCha20-Poly1305, and Bellare & Namprempre, “Authenticated Encryption” (2000).
Step 6 — Example problem.
Example problem: choosing the composition order
A protocol must encrypt a message and authenticate it with a MAC, using a separate CPA-secure cipher and a secure MAC. Compare EtM and MtE: which order lets the receiver reject forged ciphertexts before decrypting, and why does the other order invite attacks?
Solution
In EtM, the tag is computed over the ciphertext and sent alongside it; the receiver verifies the tag first and only decrypts if it is valid. Forged or tampered ciphertexts never reach the decryption code, so decryption oracles are unavailable to the attacker — this is what IND-CCA security requires. In MtE, the receiver must decrypt before it can check the tag, so malformed ciphertexts reach the decryption code; if decryption behaves differently for different padding errors (timing, error messages), the attacker gets a padding oracle that leaks plaintext information — the Lucky 13 attack on TLS 1.2’s CBC suites worked exactly this way.
Key generation and derivation §
A KDF (Key Derivation Function) derives a fixed-length key from arbitrary input. PBKDF2 (RFC 2898) iterates a PRF (HMAC) times per block:
Key stretching (bcrypt, scrypt, Argon2) adds memory and CPU cost to make brute-force attacks expensive. Salt is a random per-password value that prevents rainbow table attacks. Key separation uses domain-specific labels (e.g., "encryption", "authentication") to derive distinct keys from a master key.
KDFs bridge the symmetric and asymmetric worlds: in TLS 1.3, HKDF derives session keys from the shared secret produced by an asymmetric key exchange (ECDHE or ML-KEM). In hybrid encryption, a KEM produces a shared secret that a KDF then expands into encryption and authentication keys (see Networks for the full TLS protocol).
Details
Step 1 — The global picture. A KDF solves two different problems depending on the input. If the input is high-entropy but non-uniform (a Diffie–Hellman shared secret), use an extract-then-expand KDF like HKDF: extract a uniform pseudorandom key, then expand it into as many labeled keys as needed. If the input is low-entropy (a human password), no construction can create entropy — instead, a PBKDF makes each guess expensive, so the attacker’s offline search is slowed.
Step 2 — A concrete example. Storing a password: pick a random 128-bit salt , run PBKDF2-HMAC-SHA256 with iterations, store . A legitimate login costs one run (milliseconds); an attacker with the stolen database must run 600,000 HMACs per guessed password, per user (because of the salt). Key separation then splits the result: from a master key , derive and , so a leak in one context cannot compromise the other.
Step 3 — The main constructions. bcrypt: Blowfish-based, iterations (work factor ), 60-character output, slow by design. scrypt: memory-hard; requires blocks of bytes, resisting GPU/ASIC attacks. Argon2: winner of the Password Hashing Competition (2015); variants Argon2i (side-channel resistant), Argon2d (data-dependent), Argon2id (hybrid); parameters: memory cost , iterations , parallelism . HKDF (RFC 5869): extract , then expand ; used in TLS 1.3, SSH, and IPsec.
Step 4 — Authoritative sources. RFC 2898: PBKDF2 and RFC 5869: HKDF.
Step 5 — Example problem.
Example problem: why the salt is stored in the clear
A password database stores with the salt visible to anyone who steals the database. Since the salt is not secret, does it provide any security? What exactly does it prevent?
Solution
The salt is not meant to be secret; it prevents amortized attacks. Without salts, an attacker precomputes a rainbow table of for common passwords once and reuses it against every database forever. With a per-user random salt, the table would have to be rebuilt for each user of each database, multiplying the attacker’s work by the number of salts. Salts also prevent detecting identical passwords across users (the stored hashes differ). What the salt does not do is slow down a single targeted guess — that is the job of the iteration count (key stretching).
Now that we have a way to derive keys, the remaining question is how to establish the initial shared secret in the first place, when the two parties share no pre-existing key.
Asymmetric cryptography §
One-way functions and trapdoors. A one-way function is easy to compute but hard to invert: given , no efficient algorithm recovers . A trapdoor one-way function has a secret key that makes inversion easy: is hard to invert without , but easy with . Public-key cryptography is built on trapdoor one-way functions: the public key defines , the private key is the trapdoor . RSA uses the trapdoor of factoring; ECC uses the trapdoor of the discrete log on elliptic curves.
Diffie–Hellman key exchange: Alice picks , sends ; Bob picks , sends . Both compute . Security relies on the hardness of the discrete log problem.
Public-key encryption and key exchange (RSA, ElGamal, ECDH): encrypt with the public key, decrypt with the private key. RSA: , where . ECDH is a key exchange protocol (not an encryption scheme): both parties derive a shared secret from their public keys.
Digital signatures (RSA, ECDSA, EdDSA): sign with the private key, verify with the public key. Provides authentication and non-repudiation.
KEM (Key Encapsulation Mechanism): generates a random key and an encapsulation (ciphertext) that allows the recipient to recover the key. KEMs are asymmetric primitives used in hybrid encryption (e.g., ML-KEM in TLS 1.3). The sender encapsulates a key; the recipient decapsulates it using their private key.
Details
Step 1 — The global picture. Symmetric cryptography assumes a shared key; asymmetric cryptography removes that assumption using computational asymmetry: operations that are easy in one direction and hard in the other. Three primitives follow: key exchange (build a shared secret over a public channel), public-key encryption (anyone can encrypt to you), and signatures (only you can vouch for data). All three rest on one-way or trapdoor functions.
Step 2 — A concrete example: toy RSA. Take , , so and . Pick (coprime to 20); then (since ). To encrypt : . To decrypt: . Anyone can encrypt with ; only the holder of can invert — and with real 2048-bit primes, recovering from requires factoring , which is infeasible. You can watch the same structure interactively with the Diffie–Hellman tab of the Interactive exploration section.
Step 3 — Signature schemes. ECDSA operates on points of an elliptic curve ; signatures are pairs; it is more efficient than RSA for the same security level (256-bit EC ≈ 3072-bit RSA). EdDSA uses Edwards curves (); simpler implementation, constant-time, resistant to side-channel attacks; used in SSH, TLS 1.3, and Bitcoin (via Schnorr).
Step 4 — Hybrid encryption. TLS 1.3 uses an asymmetric KEM (or ECDHE) to establish a shared secret, then a symmetric AEAD for bulk data — the efficiency of symmetric crypto with the convenience of public keys. See Networks for the full TLS handshake.
Post-quantum cryptography §
Shor’s algorithm (1994) solves integer factoring and discrete log in polynomial time on a quantum computer, breaking RSA and ECC. NIST finalized three post-quantum standards in August 2024:
- FIPS 203 (ML-KEM): lattice-based KEM (Module-Lattice Key Encapsulation, formerly CRYSTALS-Kyber). Replaces ECDHE for key exchange.
- FIPS 204 (ML-DSA): lattice-based digital signatures (Module-Lattice Digital Signature Algorithm, formerly CRYSTALS-Dilithium). Replaces RSA/ECDSA signatures.
- FIPS 205 (SLH-DSA): hash-based signatures (SPHINCS+). Stateless, security reduces to hash collision resistance.
Lattice-based schemes rely on the hardness of the Learning With Errors (LWE) problem; hash-based schemes rely only on the security of a hash function. FALCON (FN-DSA, FIPS 206) is a lattice-based signature scheme still in development and was not in the first finalized batch.
Step 5 — Authoritative sources. RSA: “A Method for Obtaining Digital Signatures and Public-Key Cryptosystems” (1978) and FIPS 186-5: Digital Signature Standard.
Step 6 — Example problem.
Example problem: why eavesdroppers cannot follow a Diffie–Hellman exchange
Alice sends and Bob sends over a public channel; an eavesdropper sees both, plus and . Explain why the eavesdropper cannot compute the shared secret , and what would happen if they could take discrete logarithms.
Solution
To get from and , the eavesdropper would need to combine the two exponents without knowing either one. The best known generic route is to solve the discrete logarithm problem — recover from — after which computing is trivial. For large prime (2048-bit and up) or elliptic-curve groups, discrete log is believed to require about operations for a -bit security level, so the eavesdropper is stuck with the Computational Diffie–Hellman problem. If they could take discrete logarithms (e.g., with Shor’s algorithm on a large quantum computer), they would recover , then , and the entire exchange would collapse — which is exactly why post-quantum KEMs like ML-KEM are being deployed.
Zero-knowledge proofs and commitment schemes §
A commitment scheme lets a party commit to a value (publish a commitment) and later reveal it, without being able to change it. It must be binding (the commitment determines the value) and hiding (the commitment reveals nothing about the value). A simple construction: commit to by publishing for a random nonce — hiding comes from , binding from collision resistance.
A zero-knowledge proof (ZKP) lets a prover convince a verifier that a statement is true without revealing any information beyond its truth. It must satisfy completeness (an honest prover convinces the verifier), soundness (a cheating prover cannot convince the verifier of a false statement), and zero-knowledge (the verifier learns nothing else). These primitives underpin blockchain (e.g., zk-SNARKs in Zcash), secure multi-party computation, and privacy-preserving authentication. They build on the same one-way and trapdoor functions as public-key cryptography but add the properties of hiding and knowledge transfer without information leakage.
Details
Step 1 — The global picture. Encryption hides data; signatures vouch for data. Commitments and ZKPs do something neither does: they let you prove things about hidden data. A commitment is the cryptographic equivalent of sealing a value in an envelope; a ZKP is the equivalent of convincing someone the envelope contains a valid solution without opening it.
Step 2 — A concrete example: Schnorr identification. Alice wants to prove she knows the discrete log of (her private key) without revealing . She picks a random , sends the commitment ; Bob replies with a random challenge ; Alice answers with ; Bob checks . The protocol is complete (honest Alice always passes), sound (a cheater without fails for a random except with negligible probability), and zero-knowledge (Bob could simulate the whole transcript himself with random and a fitted , so the transcript proves nothing beyond Alice’s honesty). This commit–challenge–response shape is the skeleton of most ZK protocols.
Step 3 — Authoritative sources. The Knowledge Complexity of Interactive Proof-Systems (Goldwasser, Micali & Rackoff, 1985) and How to Construct Random Functions (for commitments from one-way functions).
Step 4 — Example problem.
Example problem: binding and hiding of a hash commitment
Alice commits to a bid by publishing with a random 256-bit , and reveals later. Which property stops her from changing her bid after seeing competitors’ commitments, and which property stops competitors from reading her bid? What breaks if is omitted?
Solution
Binding (from collision resistance of ) stops the bid change: to open the commitment as a different , Alice would need , i.e., a collision. Hiding (from being random and 256 bits) stops competitors: without , every is consistent with the digest, and brute-forcing jointly is infeasible. If is omitted, hiding collapses: competitors hash each plausible bid (””, “”, …) and match against the commitment — a dictionary attack, exactly like unsalted password hashing.
Interactive exploration §
The simulation below demonstrates three constructions from this page. Diffie–Hellman: set the public parameters and the private values , click Exchange, and watch both parties arrive at the same shared secret while the eavesdropper sees only public values. Block Cipher Modes: enter plaintext blocks containing a repetition (the default AB AB CD AB does), click Encrypt, and compare how ECB copies the pattern into the ciphertext while CBC and CTR hide it. Feistel Network: choose a number of rounds, click Animate, and step through the rounds to see how an invertible permutation emerges from a non-invertible round function.
Example problem §
Problem
Problem: Design a secure protocol for Alice to send a 1 MB file to Bob over an insecure channel, assuming they share no pre-existing secret. Specify the key exchange, encryption, and authentication steps.
Solution
-
Key exchange: Alice and Bob perform an ECDHE (Elliptic Curve Diffie–Hellman Ephemeral) key exchange. Alice generates an ephemeral key pair , Bob generates . They exchange and . Both compute the shared secret .
-
Key derivation: Derive session keys from using a KDF (e.g., HKDF): , .
-
Encryption: Encrypt the file with AES-256-GCM (an AEAD) using . GCM provides both confidentiality and integrity. Use a random 96-bit nonce (included in the ciphertext header).
-
Authentication: GCM’s built-in MAC authenticates both the ciphertext and any associated data (e.g., a file header). No separate MAC is needed.
-
Forward secrecy: The ephemeral keys are discarded after the session. Even if Bob’s long-term private key is later compromised, past sessions remain secure.
This is essentially what TLS 1.3 does. The total overhead is bytes (two public keys) + 12 bytes (nonce) + 16 bytes (GCM tag) per file.