Public Keys
How can two strangers agree on a secret while everyone listens?
Alice and Bob agree in public on the prime 23 and the number 5, send 8 and 19, and both arrive at the secret 2, which was never said: Diffie and Hellman's exchange of 1976. The part builds what makes it work. Merkle's puzzles give a first, quadratic gap between the parties and the eavesdropper; extended Euclid, square-and-multiply and the cyclic group of units give the toolkit; RSA is generated at 2048 bits from the series' own Miller-Rabin and proved correct by Euler and the CRT. The attacks set the key sizes: Bleichenbacher's padding oracle reads a message under a 256-bit key in 33,392 queries, Pollard's rho and a quadratic sieve factor, and baby-step giant-step, Pohlig-Hellman and index calculus take discrete logarithms. Elliptic curves escape index calculus, so 256 bits suffice, and one repeated ECDSA nonce gives away the private key. Certificates bind keys to names, and two of the series' machines run a TLS 1.3 handshake in which every check passes. The part turns on Shor's algorithm, which breaks all of it on a quantum computer. It ends with the lattices that answer it (LLL, LWE, ML-KEM's arithmetic) and with cryptography that proves and computes on secrets.
What you need. Modular arithmetic and the idea of a group; the symmetric tools of Part 29.
- Mathematics, ideas and history
- Diffie–Hellman, RSA, factoring and discrete logs, elliptic curves, PKI and TLS 1.3, lattices and ML-KEM, SNARKs, FHE, MPC
- What we build or compute
- a TLS-like handshake between two Pebbles
What you will be able to do
Degree
- Carry out a Diffie-Hellman exchange by hand with a small prime, and explain what the eavesdropper would have to compute.
- Compute a modular inverse by extended Euclid and a modular power by square-and-multiply.
- Generate a small RSA key, encrypt and decrypt with it, and explain why decryption inverts encryption.
Graduate
- Prove RSA correct by Euler's theorem and the CRT, and explain why textbook RSA needs OAEP.
- Compute a discrete logarithm by baby-step giant-step, and explain why Pohlig-Hellman forces groups of large prime order.
- Add and double points on an elliptic curve over a prime field, and recover an ECDSA key from two signatures that share a nonce.
Research
- State the LWE problem and what its worst-case to average-case reduction claims, and what is not known about the quantum hardness of lattice problems.
- Explain what the breaks of Rainbow and SIKE show about the evidence behind post-quantum schemes.
Industry
- Read a TLS 1.3 handshake: key share, certificate chain, CertificateVerify, Finished, and where forward secrecy comes from.
- Recognize a padding oracle, nonce reuse and an unauthenticated key exchange as protocol failures, not failures of the mathematics.
- Plan a migration to hybrid and post-quantum key exchange against harvest now, decrypt later.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Degree 19 min · Graduate 48 min · Research 49 min · Industry 25 min.
- 0Two strangers, one secretDegree2 min
- 1Key distribution and Merkle's puzzlesDegree3 min
- 2The toolkit: modular arithmeticDegree3 min
- 3Groups and the discrete logarithmDegree3 min
- 4Diffie-HellmanDegree3 min
- 5RSADegree4 min
- 6Bleichenbacher's oracleIndustry2 min
- 7FactoringGraduate4 min
- 8Discrete logarithmsGraduate3 min
- 9Elliptic curvesGraduate4 min
- 10SignaturesGraduate2 min
- 11Certificates and trustIndustry2 min
- 12TLS 1.3Industry2 min
- 13Shor's threatGraduate2 min
- 14LatticesGraduate4 min
- 15Zero knowledge, sharing and computing on secretsGraduate3 min
- 16Frontier: post-quantum and beyondResearch2 min
- Recap, problems, and where this comes backAll tracks3 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.
Two strangers, one secretDegree2 min
Alice and Bob have never met. They want a secret only they know, and every word they say is overheard by Eve. They agree in public on two numbers: a prime, twenty-three, and five. Alice picks a secret number, six, and Bob picks fifteen. Neither tells anyone. Alice sends five to the sixth power, reduced mod twenty-three: eight. Bob sends five to the fifteenth: nineteen. Now Alice raises Bob's nineteen to her six, and Bob raises Alice's eight to his fifteen. Both get two. Eve heard every number, twenty-three, five, eight and nineteen, and the secret two was never said. Both computed five to the power six times fifteen, by different routes. Whitfield Diffie and Martin Hellman published this in 1976, and it changed what cryptography could do.
With small numbers Eve could simply try every exponent. In practice the prime has two thousand and forty-eight bits, six hundred and seventeen decimal digits, and the exchange still takes a few hundredths of a second, even in Python. To learn the secret, Eve must find the exponent from the power: the discrete logarithm, which nobody knows how to compute at this size. Every HTTPS connection your browser makes begins with an exchange like this one, usually on an elliptic curve. And with a signature, because Alice must also know that the person she agreed a secret with is Bob, and not someone in the middle.
1Key distribution and Merkle's puzzlesDegree3 min
Everything in Part 29 assumed that the two sides already shared a key. Where does it come from? If every pair of people needs its own key, n people need n times n minus one over two keys. Eight people need twenty-eight; a million need five hundred billion. For most of history each key was carried by hand, by courier, before any message could be sent. Governments ran fleets of couriers carrying key material. A trusted centre that shares a key with everyone reduces the count, and Kerberos, in Part 55, works this way; but the centre can read everything. On the internet, strangers meet billions of times a day, and need a key immediately.
In 1974 Ralph Merkle, an undergraduate at Berkeley, proposed a way out, in a course project his professor didn't understand. Alice makes many puzzles. Each holds an identifying number and a key, locked under a deliberately weak key that takes some effort to find. Each puzzle uses a separate public salt in its hash checks and pad, preventing one weak-key lookup table from unlocking all the puzzles. The identifying number stays encrypted. Bob picks one puzzle at random, solves it, and announces its number in public. Alice looks up which key that number belongs to. Now they share it. Eve hears the number, but doesn't know which puzzle it came from, so she has to solve puzzles until she finds it: about half of them in the simple independent brute-force model. We measured Bob's search and successful agreement. Eve's table entries are modeled work, approximately n squared over four; we did not time an optimal attacker. That gap is only quadratic: a determined Eve with a big computer catches up. Barak and Mahmoody proved a quadratic barrier for classical key agreement in the ideal random-oracle model. This model is the scope of the theorem; it is not a claim about every possible concrete hash construction.
The structure was found twice. At GCHQ, the British signals agency, James Ellis argued in 1970 that encryption without a shared secret was possible. Clifford Cocks, a young mathematician, found a way in 1973: essentially RSA. Malcolm Williamson found the Diffie-Hellman exchange in 1974. All of it stayed classified. In public, Diffie and Hellman published in 1976, and Rivest, Shamir and Adleman at MIT found RSA in 1977. GCHQ told its story only in 1997. The idea in both: a key you can publish to the world, which locks a secret that only you can open. The next two chapters build the mathematics it needs.
2The toolkit: modular arithmeticDegree3 min
Public-key cryptography computes with numbers hundreds of digits long, but always on a clock. On a twelve-hour clock, nine plus seven is four: keep only the remainder after dividing by twelve. Arithmetic modulo n never lets numbers grow past n. Addition, subtraction and multiplication work as usual. Division is the question: to divide by a you need an inverse, a number that multiplied by a gives one. An inverse exists exactly when a shares no factor with n. Five times five is twenty-five, which is one on this clock, so five is its own inverse; four has none. Gauss wrote the theory down in 1801. Finding inverses quickly needs an algorithm two thousand years older.
Euclid's algorithm, from about 300 BC, finds the greatest common divisor. Divide two hundred and forty by forty-six, keep the remainder, ten; divide forty-six by ten, and so on, until the remainder is zero. The last nonzero remainder, two, is the gcd. The extension: carry two coefficients along, so that every remainder is written as some multiple of two hundred and forty plus some multiple of forty-six. At the end, two equals two hundred and forty times minus nine, plus forty-six times forty-seven. That is Bézout's identity. When the gcd is one, the same identity hands you an inverse. The inverse of seventeen modulo three thousand one hundred and twenty is two thousand seven hundred and fifty-three, a number we will meet as an RSA key. The number of steps grows only with the number of digits, so this is instant even for numbers six hundred digits long.
The other tool is raising to a huge power. To compute three to the two hundred and eighteen, modulo a thousand, don't multiply two hundred and seventeen times. Write the exponent in binary. Then read its bits from the top. For every bit, square what you have; when the bit is a one, also multiply by three. Eight squarings and five multiplications, and the answer is four hundred and eighty-nine. A two-thousand-bit exponent needs about four thousand multiplications, rather than two to the two thousand. Part 16 counted its steps, Part 20's primality test ran on it, and it will reappear on elliptic curves. With Euclid and squaring, the basic operations on six-hundred-digit numbers take milliseconds. What makes them useful for secrets is structure, the subject of the next chapter.
3Groups and the discrete logarithmDegree3 min
Take the nonzero numbers modulo a prime, twenty-three, with multiplication. Any two multiply to another one, and every one has an inverse: this is a group. Start at one and keep multiplying by five: five, two, ten, four, twenty, and so on, jumping around the circle. After twenty-two steps every number has been visited, and we are back at one. Five generates the whole group. Gauss proved that for every prime the group is cyclic like this: some number generates all of it. Going forward, from x to five to the x, is easy even for huge numbers, by repeated squaring. Going back, from five to the x to x, is the discrete logarithm. The jumps are what make it hard.
Not every number generates the group. The order of a number is how many steps it takes to come back to one. Here are all twenty-two, coloured by order. Every order is one, two, eleven or twenty-two: exactly the divisors of twenty-two. That is Lagrange's theorem: in any finite group, the order of every element divides the size of the group. It proves Fermat's little theorem at once. The group has p minus one elements, so every a raised to the p minus one is one. The same argument for the numbers coprime to n, of which there are phi of n, gives Euler's theorem. Chapter five builds RSA on it.
Here is what makes the discrete logarithm hard, for the prime one thousand and nineteen. Plot two to the x, modulo the prime, for every exponent. At first the powers grow smoothly, two, four, eight; then reduction wraps them around, and the points scatter like noise. Going backward means taking a height and finding which exponent produced it. There is no trend to follow. The best general methods, which chapter eight builds, take about the square root of p steps, and for a two-thousand-bit prime better methods exist but are still far too slow. So the map from x to g to the x is, as far as anyone knows, a one-way function: easy forward, hard to invert. Part 29 showed that one-way functions give all of symmetric cryptography. This one has extra structure, and that structure gives public keys.
4Diffie-HellmanDegree3 min
The idea is easiest with paint. Alice and Bob agree in public on a colour, yellow. Each secretly picks a colour of their own. Each mixes their secret colour into the public one, and sends the mixture. Mixing is easy; separating a mixture back into its colours is not. Alice adds her secret colour to Bob's mixture; Bob adds his to Alice's. Both end up with yellow, red and blue together: the same colour. Eve saw the yellow and both mixtures, but to get the final colour she would have to unmix one of them.
Now the mathematics. The public colour is a generator g of a group modulo a prime. The secrets are exponents. Mixing is exponentiation: Alice sends g to the a, Bob sends g to the b. Alice raises Bob's number to a, Bob raises Alice's to b, and exponents multiply, so both get g to the a b. Unmixing is the discrete logarithm. The security assumption is called computational Diffie-Hellman: from g, g to the a and g to the b, nobody can compute g to the a b. Proofs usually need a stronger one, decisional Diffie-Hellman: the shared value cannot even be told apart from a random group element. It fails in the full group modulo p, so real systems work in a subgroup of prime order. The shared value is then hashed into a key. And the same exchange on an elliptic curve, chapter nine, is smaller and faster.
Diffie-Hellman defeats a listener. It does not defeat someone who can change the messages. Mallory sits between Alice and Bob, intercepts g to the a and g to the b, and runs one exchange with each side, using her own secret. In our run Alice ends up sharing fifteen, with Mallory, and Bob shares eight, also with Mallory. Each believes the key is shared with the other. Now Mallory decrypts everything Alice sends, reads or changes it, and re-encrypts it for Bob. The exchange protects against eavesdropping, not against impersonation. The fix is for Bob to sign his half with a key Alice can verify, which needs signatures and some way to trust a public key: chapters ten and eleven.
5RSADegree4 min
Diffie and Hellman described public-key encryption but did not build it. The next year Ron Rivest, Adi Shamir and Leonard Adleman did. Pick two primes, here sixty-one and fifty-three, and multiply them: three thousand two hundred and thirty-three. This product n is public. Count how many numbers below n share no factor with it: phi of n, which is easy only if you know the two primes: three thousand one hundred and twenty. Choose a public exponent, seventeen, and compute its inverse modulo phi with Euclid: two thousand seven hundred and fifty-three, the private exponent. To encrypt the message sixty-five, raise it to the seventeenth power mod n: two thousand seven hundred and ninety. To decrypt, raise that to the private exponent, and sixty-five comes back. The pair n and e can be published. Decrypting needs d, and computing d needs the primes.
Why does this work? Because d is the inverse of e modulo phi of n, e times d is one more than a multiple of phi. So raising the ciphertext to d gives m to the e d, which is m times m to the phi, raised to some power. By Euler's theorem from chapter three, m to the phi is one, and m is left. Euler needs m to share no factor with n; for the vanishingly rare messages that do, check the equation modulo p and modulo q separately and combine the two with the Chinese remainder theorem. The security assumption is that, knowing only n and e, nobody can take e-th roots modulo n. Factoring n would break it. Whether there is an easier way to break it than factoring is still unknown.
Real keys use primes of a thousand bits or more. To find one, pick a random odd number of the right size and test it with Part 20's Miller-Rabin test, and keep going until one passes. Primes are plentiful: by the prime number theorem, about one odd number in three hundred and fifty-five at this size is prime, and our three searches took three hundred and fifty-four, ninety-nine and three hundred and sixty tries. A complete two-thousand-bit key took under a second. Decrypting directly costs twenty-nine milliseconds. Decrypting modulo p and modulo q separately, with half-size numbers, and combining by the Chinese remainder theorem, costs nine: over three times faster, which is why every implementation keeps the primes in the private key.
Raising to a power is not yet encryption. Textbook RSA is deterministic, so by Part 29's definition it is not secure: an attacker can encrypt guesses and compare. It is also malleable. Multiply a ciphertext by two to the e, and the message inside doubles. We encoded pay Bob one hundred dollars as a number, multiplied its ciphertext, and it decrypted to exactly twice the number. The standard fix is optimal asymmetric encryption padding, OAEP, from Mihir Bellare and Phillip Rogaway: mix the message with fresh randomness through two hash-based masks before encrypting. Now two encryptions of the same message differ, and the round trip checks our encoding. The same trapdoor signs: raise a hash of the message to the private exponent, and anyone can check it with the public one. Hashing first matters, because raw signatures multiply too. Use a standard signature encoding in practice; the arithmetic alone does not define a secure scheme.
6Bleichenbacher's oracleIndustry2 min
For twenty years, TLS used RSA to send the session key, with a padding format called PKCS one version one point five. The padded message starts with the bytes zero and two, then random nonzero bytes, a zero, and the message. A server decrypting a ciphertext checks this format, and early servers sent a different error when it was wrong. That is an oracle, like Part 29's padding oracle. Combine it with malleability. Multiply the ciphertext by s to the e, and the server is checking m times s. Whenever it says the padding is valid, the attacker learns that m times s, modulo n, lies in a narrow window. Each answer cuts down the set of possible messages. Daniel Bleichenbacher showed in 1998 how to choose the s values so the set shrinks to a single number.
We built a server that answers only valid or invalid, and ran the attack. The curve shows how many bits of uncertainty remain about the message. For a two-hundred-and-fifty-six-bit key it falls slowly while the attacker searches for the first valid s, then steeply, about a bit per query. Thirty-three thousand queries in all; for a three-hundred-and-eighty-four-bit key, a hundred and twenty-nine thousand. Out comes the message, with no key and no factoring. Against real key sizes the attack takes around a million queries, which gave it its name. Servers kept leaking the bit, through error messages and timing: in 2017 the ROBOT study found it still working against major websites. TLS 1.3 removed RSA key transport altogether, and uses only Diffie-Hellman.
7FactoringGraduate4 min
The simplest fast factoring method is John Pollard's, from 1975. Pick a starting number and iterate: square it, add one, reduce modulo n. The values look random. Now imagine reducing them, also, modulo the factor p we are looking for, one thousand and nine. There are only p possible values, so by the birthday paradox they start repeating after about the square root of p steps. Here, after a tail of seven values, the sequence falls into a cycle of fourteen. Drawn out, it has the shape of the Greek letter rho. We cannot see the values mod p, but we don't need to. A repeat mod p means p divides the difference of two values, so the gcd of that difference with n is p. And it is: one thousand and nine. Part 17's tortoise-and-hare trick detects the cycle without storing the sequence.
How does rho scale? We factored products of two equal-sized primes, from ten digits to thirty-four. Rho needs about the square root of the smaller prime, the fourth root of n, so its time grows exponentially in the number of digits: a straight line on this logarithmic scale. The quadratic sieve, which we build next, grows more slowly than any exponential: sub-exponentially. In our Python, at these small sizes, the two are close: at thirty-four digits rho took forty-three seconds and the sieve eighty-seven. But the sieve's curve bends. Past about forty digits it wins, and the gap then grows without limit. For RSA-sized numbers, only the sieves matter.
The sieve rests on an old idea of Fermat's, sharpened by Carl Pomerance in 1981. If you can find x and y whose squares agree modulo n, but which are not equal or opposite, then n divides x minus y times x plus y, and a gcd splits it. To build such squares, take x just above the square root of n, so that x squared minus n is fairly small, and keep only the x for which it is smooth: a product of small primes. Here is one from our run: a twelve-digit value that factors entirely into primes below thirteen hundred. Finding them is a sieve, like Eratosthenes': for each small prime, mark the positions it divides, rather than testing each value. Write each smooth value's exponents mod two as a vector. A set of vectors summing to zero, which Gaussian elimination over the two-element field finds, multiplies to a perfect square on both sides. For our twenty-digit number: a hundred and sixteen small primes, a hundred and twenty-seven relations, a combination of forty-six of them, and the factor.
The fastest known method is the number field sieve, from the early nineteen-nineties, which takes the same idea into algebraic number fields. Its running time grows like the exponential of the cube root of the number of digits, roughly. Public records track it: a hundred digits in 1991; RSA-155, a five-hundred-and-twelve-bit key, in 1999; RSA-250, eight hundred and twenty-nine bits, in 2020, at a cost of about two thousand seven hundred core-years. A two-thousand-and-forty-eight-bit key, six hundred and seventeen digits, is far beyond this line, and is rated at about a hundred and twelve bits of security. But the curve is sub-exponential, so key sizes must grow quickly for more security: three thousand and seventy-two bits for a hundred and twenty-eight, fifteen thousand for two hundred and fifty-six. Elliptic curves, chapter nine, do much better.
8Discrete logarithmsGraduate3 min
Chapter three left a question: how fast can g to the x be undone? Trying every x takes p steps. Daniel Shanks found a square root in 1971. Write the unknown x as i times m plus j, with m about the square root of p. First take baby steps: store g to the j for every j below m. Then take giant steps from the target: h, h divided by g to the m, by g to the two m, and so on, looking each one up in the table. When one matches, x is read off. About two square roots of p operations, and a square root's worth of memory. Our runs: each four more bits of p multiply the time by about five, close to the four a square root predicts. Pollard's rho does the same with almost no memory.
The square root is of the group's order, and the order's structure matters. Stephen Pohlig and Martin Hellman showed in 1978 that a discrete logarithm splits into one smaller logarithm for each prime factor of p minus one, glued back together by the Chinese remainder theorem. Here is an eighty-four-bit prime whose p minus one is a product of small primes. The largest is a hundred and nine, so every piece is tiny, and the whole logarithm takes under a millisecond. A safe prime is twice a prime plus one. Then p minus one has a huge prime factor, and nothing beats the full square root. So Diffie-Hellman groups are built from safe primes, or work in a subgroup of large prime order.
For the numbers modulo p there is something better than square roots, because numbers can be factored. If some power of g happens to factor into small primes, its exponent is a linear combination of the logarithms of those primes. Collect enough such smooth powers and solve the linear system, and you know the logarithm of every small prime. Then multiply the target by random powers of g until the product is smooth, and its logarithm falls out. Ours works on a thirty-bit prime in a tenth of a second. Index calculus is sub-exponential, like the sieves, which is why Diffie-Hellman over integers needs primes of two thousand bits. Worse, the expensive first stage depends only on the prime, not on the exchange. In 2015 the Logjam researchers showed that servers still accepting old five-hundred-and-twelve-bit export groups could be broken in minutes after one precomputation, and that a handful of shared thousand-bit primes were within reach of a national agency. Elliptic curve points cannot be factored into small pieces. There, only the generic square-root attacks are known.
9Elliptic curvesGraduate4 min
An elliptic curve is the set of points where y squared equals a cubic in x. Here is y squared equals x cubed minus x plus one. The remarkable fact is that its points can be added. Take two points, P and Q. The line through them meets the curve in exactly one more point, R: a cubic has three roots, and we know two. Reflect R in the x-axis. That point is defined to be P plus Q. With these whole-number points, minus one, one plus zero, one is one, minus one. With one extra point at infinity as zero, where vertical lines meet, and reflection as negation, the points form a group. Associativity, that adding P and Q first then R gives the same as Q and R first, is true and takes real work to prove. It is the curve's deepest property, and we will simply check it numerically.
Adding a point to itself uses the tangent line. At P, minus one, one, the slope of the curve is one. The tangent meets the curve again at three, five. Reflect, and two P is three, minus five. In coordinates, the slope, the new x and the new y come from a few lines of algebra. They use only addition, subtraction, multiplication and division. So the same formulas make sense over any field, including the integers modulo a prime, where the curve stops being a curve and becomes a scatter of points.
Over the integers modulo ninety-seven, the curve y squared equals x cubed plus two x plus three becomes this. Ninety-nine points, and the point at infinity: a group of a hundred. The symmetry about the middle is the reflection, y to minus y. Take a point G and keep adding it: G, two G, three G. The multiples jump around the grid with no visible order, fifty of them before they return to zero. Given a multiple Q equals k times G, finding k is the elliptic-curve discrete logarithm. Computing k times G is easy: double and add, chapter two's square and multiply in new clothes. On the standard curve P-256, with two-hundred-and-fifty-six-bit numbers, it takes twenty milliseconds in Python.
Why use curves at all? Because their keys are small. For the same security, RSA needs a three-thousand-bit modulus where a curve needs two hundred and fifty-six bits; at higher levels the gap widens. The reason is the last chapter's index calculus: points on a good curve cannot be broken into small factors, so the only known attack is a generic square root. Victor Miller and Neal Koblitz proposed curve cryptography independently in 1985. NIST standardised P-256, and in 2006 Daniel Bernstein designed Curve25519 to be fast and hard to implement wrongly. Its X25519 function uses a Montgomery ladder, which performs the same operations whatever the key bits are. Ours matches the RFC's test vector, and two parties agree on a secret. Almost every TLS connection today begins with exactly this computation.
10SignaturesGraduate2 min
Encryption hides; a signature proves who wrote something. The elliptic-curve digital signature algorithm, ECDSA, signs most of the web's certificates and most Bitcoin transactions. To sign, pick a fresh random number k, take the x coordinate of k times G as r, and combine k, the message's hash and the private key into s. To verify, anyone holding the public key computes two multipliers from s and checks that a combination of G and Q lands back on r. It works because that combination is exactly k times G. Only the holder of d can produce such a pair, while anyone can check it. Because bad random numbers ruin signatures, RFC 6979 derives k deterministically from the key and the message with HMAC. Our implementation reproduces the standard's test signature exactly. Everything hangs on k: it must be secret, uniform, and never used twice.
Here is what happens if k repeats. Two signatures on two different messages, made with the same nonce. The first half of each signature, r, is identical: the giveaway. Subtract the two s values: the private key cancels, and what is left gives k from the two hashes. With k known, one line of algebra gives the private key d. Our recovery finds both, correctly, and signs a message the key's owner never approved; it verifies. This is not hypothetical. In 2010 the fail0verflow group found that Sony signed PlayStation 3 software with the same k every time, and recovered the master signing key from two signatures. Even nonces that are merely biased by a few bits leak the key, given enough signatures, through the lattice methods of chapter fourteen.
11Certificates and trustIndustry2 min
A signature tells you which key signed. It does not tell you whose key that is. A certificate binds a name to a public key, and is signed by a certificate authority. Here the website pebble dot example has a key, certified by an intermediate authority, which is certified in turn by a root authority. The root's key is not certified by anyone: it ships inside your browser or operating system, in a list of about a hundred and fifty root certificates. Our chain, signed with our ECDSA, verifies. Change one character of the website's name and the signature fails. A certificate the attacker signs with their own key fails too, because no trusted root vouches for it. So trust is delegated: you trust the roots, the roots trust the intermediates, and they vouch for websites.
The weakness of this system is its breadth. Any trusted root can certify any name, so the least careful authority sets the security of every website. In 2011 the Dutch authority DigiNotar was broken into, and certificates for google dot com, signed by a trusted root, were used to intercept users in Iran. DigiNotar was removed from every browser and went bankrupt. The response, from Ben Laurie and Adam Langley at Google, was Certificate Transparency: every certificate must be recorded in public, append-only logs. The logs are Part 29's Merkle trees. A short proof shows that a certificate is in the log, and another that the log has only ever grown, never been rewritten. Since 2018 Chrome rejects certificates that cannot prove they were logged, so a misissued certificate can no longer be used in secret. And since Let's Encrypt began issuing free, automated certificates in 2015, most of the web has moved to HTTPS.
12TLS 1.3Industry2 min
3. Everything so far comes together in TLS 1.3, the protocol under HTTPS, standardised in 2018. We ran a version of it between two of our machines. The client sends a hello containing a fresh X25519 public key. The server answers with its own. Both can now compute the same shared secret, and every later message is encrypted. The server's next flight, encrypted, carries its certificate chain, a signature over everything said so far, and a MAC called Finished. The signature is what defeats chapter four's man in the middle: only the holder of the certified key could have signed this transcript. The client checks it all and sends its own Finished MAC. Then application data flows, under authenticated encryption. One round trip, and every check passed.
Where do all those keys come from? The shared secret from the exchange goes through HKDF, a key-derivation function built from HMAC by Hugo Krawczyk; ours matches its standard's test vectors. From one secret it derives separate keys for the handshake, for the Finished MACs and for application data, each labelled, and each mixed with a hash of the transcript. So if an attacker changes a single byte of either hello, nothing verifies. The exchange keys are ephemeral, used once and discarded. The server's long-term key only signs. That is forward secrecy: an attacker who records today's traffic and steals the server's key next year still cannot read it. With the old RSA key transport, they could. TLS 1.3 also deleted most of what earlier versions got wrong: RSA key transport, CBC modes, custom groups, compression and renegotiation, all the subjects of famous attacks.
13Shor's threatGraduate2 min
Every public-key system so far rests on factoring or discrete logarithms. In 1994 Peter Shor showed that a quantum computer could do both. The key is that factoring reduces to finding a period. Take N equals fifteen and a equals seven, and list the powers of seven mod fifteen: one, seven, four, thirteen, one, and around again. The period is four. Seven to the fourth is one, so fifteen divides seven squared minus one times seven squared plus one, and the gcds give three and five. The same works for twenty-one and thirty-five. For a large N, the period is astronomically long, and no classical method finds it faster than factoring itself. A quantum computer can put all the powers in superposition and read the period off with the quantum Fourier transform, in polynomial time. Part 53 builds it, and factors fifteen on our simulator. The same idea solves discrete logarithms, in any group. RSA, Diffie-Hellman and elliptic curves fall together.
How close is the threat? The largest quantum computers today have about a thousand physical qubits, too noisy for Shor's algorithm at any useful size. Breaking a two-thousand-bit RSA key needs error correction, Part 28's subject transplanted into quantum hardware; a 2025 estimate by Craig Gidney put it at under a million noisy qubits running for about a week. When such a machine will exist, nobody knows. But an adversary can record encrypted traffic now and decrypt it whenever the machine arrives, so any secret that must last a decade is already exposed. In August 2024 the US standards institute published the first post-quantum standards: a key-encapsulation mechanism, ML-KEM, and two signature schemes. Browsers and large websites have already switched on hybrid key exchange, X25519 together with ML-KEM, which stays secure as long as either one does. Symmetric cryptography is in much better shape: Grover's algorithm only halves the effective key length. The next chapter builds the mathematics under ML-KEM.
14LatticesGraduate4 min
A lattice is a regular grid of points in space: all whole-number combinations of a few basis vectors. The same lattice has many bases. These two long, nearly parallel vectors, ninety, one hundred and twenty-three and fifty-six, seventy-six, generate exactly the same points as these two short ones. Gauss's reduction, subtracting multiples of one vector from the other, finds the short basis in a few steps. In two dimensions that is easy. In hundreds of dimensions, finding a short vector given a bad basis is believed to be hard, and unlike factoring, no quantum algorithm is known to help. The LLL algorithm of Arjen Lenstra, Hendrik Lenstra and László Lovász, from 1982, finds a fairly short vector in polynomial time: within an exponential factor of the shortest. That factor is the gap cryptography lives in.
LLL first appeared in cryptography as a weapon. In 1978 Merkle and Hellman proposed encrypting a string of bits as the sum of a subset of public weights. Here are some of the twenty weights of ours. The trapdoor was an easy, superincreasing sequence disguised by modular multiplication. Shamir broke it in 1982, and Lagarias and Odlyzko showed that for such knapsacks the secret bits form an unusually short vector in a lattice built from the weights. Our LLL finds it, and all twenty bits. The same tool finds ECDSA keys from biased nonces and breaks RSA with badly chosen small exponents. So lattice-based schemes must choose parameters far beyond the reach of LLL and its stronger successors.
The problem post-quantum encryption uses is Oded Regev's learning with errors, from 2005. A secret vector s; a public random matrix A; and b, which is A times s plus a small random error, everything modulo q. Without the error, Gaussian elimination would find s instantly. The small noise makes it, as far as anyone knows, hard: it is a lattice problem in disguise. Regev proved something unusual: breaking random instances is as hard as solving the worst-case lattice problem, by a quantum reduction. Cryptography rarely has guarantees that strong. To encrypt a bit, add up a random subset of the public samples and add the bit times half of q. Decryption subtracts the secret's contribution and is left with the bit times q over two, plus a little accumulated noise. Here are four hundred decryptions: zeros land near zero, ones near q over two, far from the boundary. Every one decrypted correctly.
Plain LWE needs enormous keys, so the standard uses structure. ML-KEM, formerly called Kyber, works with polynomials modulo x to the two hundred and fifty-six plus one, with coefficients modulo three thousand three hundred and twenty-nine, arranged in small vectors and matrices. Multiplying polynomials is done with the number-theoretic transform, Part 19's FFT over a finite field: in our Python, about twelve times faster than schoolbook multiplication. We implemented the arithmetic of the smallest parameter set, and encrypted a hundred random messages of two hundred and fifty-six bits. Every bit decrypted correctly. Keys are eight hundred bytes and ciphertexts seven hundred and sixty-eight: bigger than elliptic curves, small enough for every TLS handshake. For signatures there is a lattice scheme, ML-DSA, and a conservative one built only from hash functions, SLH-DSA. Its ancestor is Leslie Lamport's one-time signature from 1979: publish hashes of two secrets for each bit of the message hash, and sign by revealing one secret per bit. Big, and usable once. A Merkle tree over many one-time keys turns it into a scheme for many signatures, whose security rests only on the hash function.
15Zero knowledge, sharing and computing on secretsGraduate3 min
Public-key ideas do more than encrypt and sign. Claus Schnorr's protocol proves that you know a discrete logarithm without revealing it. The prover commits to a random power of g. The verifier sends a random challenge. The prover answers with k plus e times x, which, because k is random, says nothing about x by itself. The verifier checks one equation. As in Part 27, a simulator who knows the challenge in advance can produce transcripts that look the same without knowing x: zero knowledge. Amos Fiat and Adi Shamir's trick replaces the verifier with a hash of the commitment and a message, and the proof becomes a signature. Ours verifies. Ed25519, the signature in SSH and Signal, is Schnorr on an elliptic curve, and Bitcoin adopted Schnorr signatures in 2021.
A key that unlocks everything should not live in one place, or with one person. Adi Shamir's answer, from 1979, is a polynomial. Make the secret the value at zero of a random polynomial of degree two. Hand out its values at one, two, three, four and five as shares. Any three shares determine the polynomial, by Part 28's Lagrange interpolation, and so the secret. Over the integers modulo a prime, with our five shares: shares one, two and three give thirty-one thousand three hundred and thirty-seven, and so do two, four and five. Two shares are consistent with every possible secret, so they reveal nothing at all: here they produce garbage. The shares are exactly a Reed-Solomon codeword. The scheme guards backup keys and threshold signatures, including the recovery of the internet's DNSSEC root key.
Two more ideas complete the picture. In multiparty computation, several parties each hold a private input, and together compute a function of all of them, learning only the result. Andrew Yao's garbled circuits of 1986, and Goldreich, Micali and Wigderson's protocol a year later, showed that any function can be computed this way. In 2008 Danish sugar-beet farmers set their contract prices by an auction run as a multiparty computation; today it checks passwords against breach lists without revealing them. Fully homomorphic encryption goes further: anyone can compute on ciphertexts, and only the key holder can read the result. Lattice encryption allows it, but each operation adds noise, and after a while the noise swamps the message. In 2009 Craig Gentry found the way out, bootstrapping: evaluate the decryption itself homomorphically, which removes the old noise. Once a trillion times slower than plain computation, it now runs in production for some private lookups. And differential privacy, from AI, Built part 31, protects what is learned from data that is released.
16Frontier: post-quantum and beyondResearch2 min
Post-quantum cryptography rests on younger assumptions, and some have not survived. Lattices and hash functions became standards in 2024. In 2025 a code-based scheme, HQC, built on Part 28's mathematics, was chosen as a backup with a different foundation. But in 2022 two leading candidates fell. Ward Beullens broke the Rainbow signature scheme with a weekend on a laptop. Wouter Castryck and Thomas Decru broke SIKE, based on maps between elliptic curves, in about an hour on one core, using a theorem from 1997 that nobody had connected to it. The lesson is old: an assumption earns trust only by surviving years of attack. That is why new systems combine a classical and a post-quantum algorithm, and why the standards keep backups built on different mathematics.
Even lattices carry uncertainty. Their security levels are estimates: the best known reduction attacks, extrapolated to hundreds of dimensions. Those estimates have moved, as better sieving algorithms took bits off the security of every scheme. In April 2024 a preprint claimed a quantum algorithm solving learning with errors in polynomial time, which would have broken the new standards before they were published. Within ten days, readers found a bug, and the claim was withdrawn. Nothing proves that lattice problems resist quantum computers. As with factoring before Shor, we know only that nobody has found a way.
Recap, problems, and where this comes backAll tracks3 min
What we built in this part. Merkle's puzzles, and the number theory of groups, from Euclid to Lagrange. Diffie-Hellman, and RSA from scratch, with the padding oracle that haunted it for twenty years. Factoring by rho and by a sieve, and discrete logarithms by baby steps, Pohlig-Hellman and index calculus, which set the key sizes. Elliptic curves, ECDSA, and the repeated nonce that gave away a console's key. Certificates and a TLS 1.3 handshake. And Shor's threat, with the lattices that answer it.
Where this comes back. Part 37's QUIC carries TLS 1.3 inside the transport protocol itself. Part 38 uses signatures to reach agreement when some machines lie. Part 41 signs software releases, and Part 43 puts mutual TLS between every pair of services. Part 53 runs Shor's algorithm on our quantum simulator. And Part 55 returns to authentication: passkeys, and a famous protocol whose flaw went unnoticed for seventeen years.
In practice. Use TLS 1.3 everywhere, with certificates renewed automatically. Prefer X25519, Ed25519 or P-256, and RSA only with large keys. Let a vetted library make signatures, with deterministic or well-seeded nonces. Turn on hybrid post-quantum key exchange, and find out which of your secrets must stay secret for more than a decade. And keep private keys in hardware, with backups split among people.
Six problems, with full solutions in the part's notes. Pause on any of them. The fifth is a build problem: a hybrid post-quantum handshake between our machines. The last, marked with a star, is a research problem: where small lattice attacks stop working is a question the standards depend on, and the notes say where to start.
That completes Act Five, on limits and secrets. Next, Act Six: one machine, many programs. Part 31 builds the kernel: how time-sharing gave every user the illusion of a whole computer, the protection that required, processes and system calls, the scheduler, and the queueing theory that explains why a busy server feels so much slower than a quiet one. Part 31, The Kernel.
The books and papers this part follows are on screen and in the notes. Thank you for watching.
Where it goes next. Part 37's QUIC carries TLS 1.3 inside the transport, Part 38 uses signatures to reach agreement when some machines lie, Part 41 signs software releases and Part 43 puts mutual TLS between services. Part 53 runs Shor's algorithm on the series' quantum simulator, and Part 55 returns to authentication with passkeys.
Key results
The part's results in one place, for revision.
Try it
Lab 30 · Easy forwards, a square root backwards: Diffie-Hellman, RSA and their generic attacks
Redo the film's exchange (p = 23, g = 5) and its RSA example, then break Diffie-Hellman by baby-step giant-step and factor semiprimes by Pollard's rho as the keys grow, and check that the attacker's work grows like 2^(bits/2) and 2^(bits/4) while the user's grows like the number of bits. Finally recover a P-256 signing key from two signatures that share a nonce.
python -m videos.cs.labs 30
needs numpy, scipy, matplotlib · download lab30.py ·
source on GitHubDiffie-Hellman, p = 23, g = 5 A = 8, B = 19, shared 2 = 2 (the film: 8, 19, 2)
RSA, p = 61, q = 53, e = 17 d = 2753, 65 -> 2790 -> 65 (the film: 2753, 2790, 65)
discrete log, 16-bit prime table of 255 entries sqrt(p) = 254 user: about 32 multiplications
discrete log, 20-bit prime table of 781 entries sqrt(p) = 781 user: about 40 multiplications
discrete log, 24-bit prime table of 3,574 entries sqrt(p) = 3,573 user: about 48 multiplications
discrete log, 28-bit prime table of 13,082 entries sqrt(p) = 13,082 user: about 56 multiplications
discrete log, 32-bit prime table of 46,879 entries sqrt(p) = 46,878 user: about 64 multiplications
factoring, 40-bit modulus rho: median 1,662 steps n^(1/4) = 1,024
factoring, 48-bit modulus rho: median 6,270 steps n^(1/4) = 4,096
factoring, 56-bit modulus rho: median 24,830 steps n^(1/4) = 16,384
factoring, 64-bit modulus rho: median 100,094 steps n^(1/4) = 65,536
growth per key bit log2(work): BSGS 0.50 (theory 1/2) rho 0.25 (theory 1/4)
ECDSA, one nonce used twice nonce recovered: True private key recovered: True forgery verifies: True
The user's cost grows with the number of key bits and the generic attacker's with a power of two of it, so adding bits wins; a repeated nonce or a missing signature loses whatever the key length.
The code (109 lines; it asserts its own result)
"""Lab 30: run Diffie-Hellman and RSA, then measure what the attacker pays: square roots, not polynomials."""
from videos.coursekit import labs
import math
import random
import numpy as np
from explainer.cs.algo import pubkey as P
TITLE = "Easy forwards, a square root backwards: Diffie-Hellman, RSA and their generic attacks"
GOAL = ("Redo the film's exchange (p = 23, g = 5) and its RSA example, then break Diffie-Hellman by baby-step "
"giant-step and factor semiprimes by Pollard's rho as the keys grow, and check that the attacker's work grows "
"like 2^(bits/2) and 2^(bits/4) while the user's grows like the number of bits. Finally recover a P-256 "
"signing key from two signatures that share a nonce.")
TASKS = [
"Extend DLOG_BITS to 36 and 40. How long does baby-step giant-step take, and how much memory does its table need at 2048 bits?",
"Pick a prime p with p - 1 a product of small primes and solve the logarithm with P.pohlig_hellman. Why are safe primes used?",
"Sign the two messages with the default RFC 6979 nonces instead of a fixed k. What does P.ecdsa_nonce_reuse return now, and why?",
]
DLOG_BITS = (16, 20, 24, 28, 32)
RSA_BITS = (40, 48, 56, 64)
def run(seed=0):
rng = random.Random(int(np.random.default_rng(seed).integers(2 ** 31)))
lab = labs.Lab()
# 1. the hook: p = 23, g = 5, secrets 6 and 15
A, B = pow(5, 6, 23), pow(5, 15, 23)
lab.row("Diffie-Hellman, p = 23, g = 5", f"A = {A}, B = {B}, shared {pow(B, 6, 23)} = {pow(A, 15, 23)} (the film: 8, 19, 2)")
assert (A, B, pow(B, 6, 23), pow(A, 15, 23)) == (8, 19, 2, 2)
for _ in range(20): # and in a 61-bit group: both sides agree, Mallory splits them
p = 2 ** 61 - 1
a, ga = P.dh_keypair(p, 3, rng)
b, gb = P.dh_keypair(p, 3, rng)
assert pow(gb, a, p) == pow(ga, b, p)
m = P.dh_mitm(23, 5, rng)
assert m["alice"] == m["mallory_with_alice"] and m["bob"] == m["mallory_with_bob"], "no authentication, no secret"
# 2. RSA: the film's toy key, and a 512-bit key from the series' Miller-Rabin
toy = {"n": 61 * 53, "e": 17, "d": P.inv_mod(17, 60 * 52)}
c = P.rsa_enc(65, toy)
lab.row("RSA, p = 61, q = 53, e = 17", f"d = {toy['d']}, 65 -> {c} -> {pow(c, toy['d'], toy['n'])} (the film: 2753, 2790, 65)")
assert (toy["d"], c, pow(c, toy["d"], toy["n"])) == (2753, 2790, 65)
key = P.rsa_keygen(512, rng)
for _ in range(5):
msg = rng.randrange(key["n"])
ct = P.rsa_enc(msg, key)
assert P.rsa_dec(ct, key) == P.rsa_dec(ct, key, use_crt=False) == msg
assert key["p"] * key["q"] == key["n"] and key["e"] * key["d"] % math.lcm(key["p"] - 1, key["q"] - 1) == 1
# 3. the attacker: baby-step giant-step on the discrete log, Pollard's rho on the modulus
table, logp = [], []
for bits in DLOG_BITS:
p = P.random_prime(bits, rng)
g = P.find_generator(p)
x = rng.randrange(2, p - 1)
found, size = P.bsgs(g, pow(g, x, p), p)
assert found == x and abs(size / math.sqrt(p) - 1) < 0.01
table.append(size)
logp.append(math.log2(p))
lab.row(f"discrete log, {bits}-bit prime", f"table of {size:,} entries sqrt(p) = {math.sqrt(p):,.0f} user: about {2 * bits} multiplications")
steps = []
for bits in RSA_BITS:
runs = []
for _ in range(9):
p, q = P.random_prime(bits // 2, rng), P.random_prime(bits // 2, rng)
if p == q:
continue
f, st = P.pollard_rho(p * q, rng)
assert f in (p, q)
runs.append(st)
steps.append(float(np.median(runs)))
lab.row(f"factoring, {bits}-bit modulus", f"rho: median {steps[-1]:,.0f} steps n^(1/4) = {2 ** (bits / 4):,.0f}")
slope_dlog = np.polyfit(logp, np.log2(table), 1)[0]
slope_rho = np.polyfit(RSA_BITS, np.log2(steps), 1)[0]
lab.row("growth per key bit", f"log2(work): BSGS {slope_dlog:.2f} (theory 1/2) rho {slope_rho:.2f} (theory 1/4)")
assert abs(slope_dlog - 0.5) < 0.02 and 0.1 < slope_rho < 0.45, "square-root attacks: exponential in the key length"
# 4. one repeated nonce gives away an ECDSA key (P-256)
d, Q = P.ec_keypair(P.P256, rng)
k = rng.randrange(1, P.P256.n)
m1, m2 = b"firmware 3.55", b"firmware 3.56"
s1, s2 = P.ecdsa_sign(d, m1, k=k), P.ecdsa_sign(d, m2, k=k)
k_found, d_found = P.ecdsa_nonce_reuse(m1, s1, m2, s2)
forged = P.ecdsa_sign(d_found, b"anything at all")
lab.row("ECDSA, one nonce used twice", f"nonce recovered: {k_found == k} private key recovered: {d_found == d} forgery verifies: {P.ecdsa_verify(Q, b'anything at all', forged)}")
assert s1[0] == s2[0] and k_found == k and d_found == d and P.ecdsa_verify(Q, b"anything at all", forged)
lab.note = ("The user's cost grows with the number of key bits and the generic attacker's with a power of two of "
"it, so adding bits wins; a repeated nonce or a missing signature loses whatever the key length.")
fig, ax = labs.figure(2, size=(11, 4.2))
grid = np.linspace(14, 34, 20)
ax[0].semilogy(DLOG_BITS, table, "o", color=labs.RED, label="baby-step giant-step: table entries")
ax[0].semilogy(grid, 2 ** (grid / 2), color=labs.RED, lw=1, alpha=0.7, label="2^(bits/2)")
ax[0].semilogy(grid, 2 * grid, color=labs.GREEN, label="the user: about 2 · bits multiplications")
ax[0].set(title="Discrete logarithm: user against attacker", xlabel="bits of the prime p", ylabel="operations",
xticks=DLOG_BITS)
ax[0].legend()
grid = np.linspace(38, 66, 20)
ax[1].semilogy(RSA_BITS, steps, "o", color=labs.GOLD, label="Pollard's rho: median steps")
ax[1].semilogy(grid, 2 ** (grid / 4), color=labs.GOLD, lw=1, alpha=0.7, label="2^(bits/4) = n^(1/4)")
ax[1].semilogy(grid, 2 ** (grid / 2), color=labs.MUTED, ls="--", label="trial division: 2^(bits/2)")
ax[1].set(title="Factoring a semiprime n = pq", xlabel="bits of the modulus n", ylabel="steps", xticks=RSA_BITS)
ax[1].legend()
lab.fig = fig
return lab
Now change it
- Extend DLOG_BITS to 36 and 40. How long does baby-step giant-step take, and how much memory does its table need at 2048 bits?
- Pick a prime p with p - 1 a product of small primes and solve the logarithm with P.pohlig_hellman. Why are safe primes used?
- Sign the two messages with the default RFC 6979 nonces instead of a fixed k. What does P.ecdsa_nonce_reuse return now, and why?
Problems, with solutions
Try each problem before opening its solution.
-
RSA is always correct. Prove that RSA decryption is correct for every m in ℤ_n, including those sharing a factor with n, using the CRT.
Solution
Write ed = 1 + k(p − 1)(q − 1), and work modulo p first.
- If p ∤ m, Fermat gives m^{p−1} ≡ 1. So m^{ed} = m·(m^{p−1})^{k(q−1)} ≡ m.
- If p | m, both sides are 0 mod p.
Either way m^{ed} ≡ m (mod p), and the same holds mod q. Since p and q are distinct primes, the CRT says the two congruences determine m^{ed} mod n = pq, so m^{ed} ≡ m (mod n).
-
Knowing too much factors n. Show that knowing φ(n) for n = pq factors n. Show also that knowing e and d factors n with high probability.
Solution
From φ(n) = n − (p + q) + 1 we get p + q = n − φ(n) + 1. Since pq = n, p and q are the roots of x² − (n − φ + 1)x + n.
From e and d: ed − 1 is a multiple of λ(n). Write ed − 1 = 2ᵗr with r odd. Pick a random a and compute a^r, a^{2r}, …. The sequence reaches 1, and the value just before is a square root of 1. With probability at least ½ over a, this root is not ±1, as in Miller–Rabin. Then x² ≡ 1 with x ≢ ±1, so gcd(x − 1, n) is p or q.
So publishing d is as bad as publishing the factors. A server that loses d must change n, not only d.
-
Pohlig–Hellman's cost. Show that Pohlig–Hellman takes O(∑ eᵢ(log n + √qᵢ)) group operations in a group of order n = ∏ qᵢ^{eᵢ}.
Solution
For each prime power qᵉ:
- Raise g and h to the power n/qᵉ, which takes O(log n) operations. This moves them into the subgroup of order qᵉ.
- Find the log there one base-q digit at a time. Digit j needs one exponentiation to strip the digits already found, O(log n) operations, and one discrete log in the subgroup of order q, O(√qᵢ) by BSGS.
That makes eᵢ digits, each O(log n + √qᵢ), plus O(log n) for the projection. Summing over i, and adding a negligible CRT, gives the bound. The cost is governed by the largest prime factor of the group order, which is why groups must have one of at least 2²⁵⁶.
-
ECDSA's fragility. Derive the nonce-reuse recovery. Then show that knowing k for a single signature reveals d.
Solution
A signature satisfies s ≡ k⁻¹(z + rd) (mod n). With the same k (hence the same r) for messages with hashes z₁ and z₂:
- s₁ − s₂ ≡ k⁻¹(z₁ − z₂), so k ≡ (z₁ − z₂)(s₁ − s₂)⁻¹ (when s₁ ≠ s₂).
- Then d ≡ (s₁k − z₁)r⁻¹.
The second line needs only k, so a single signature whose nonce leaks, by reuse, a weak generator or a side channel, gives d. Chapter 10 recovered both on P-256.
-
Build: a hybrid handshake. Extend the TLS-like handshake to a hybrid, X25519 plus this part's K-PKE, and check that both sides derive the same keys.
Solution
- The client adds a K-PKE public key to its ClientHello, next to its X25519 share.
- The server picks a random 32-byte secret m, encrypts its 256 bits under that public key, and returns the ciphertext with its X25519 share.
- Both sides compute IKM = X25519 secret ‖ m and feed it to HKDF-Extract in place of the X25519 secret alone. The client gets m by decrypting.
- Put both the public key and the ciphertext in the transcript, so the Finished MACs and the signature cover them.
The derived keys match whenever decryption succeeds; chapter 14 measured no failures in 25,600 bits. The combination is secure if either component is: X25519 against classical attackers, K-PKE against quantum ones.
One caveat: our K-PKE is only CPA-secure. ML-KEM wraps it in a Fujisaki–Okamoto transform. It re-encrypts the decrypted message and compares with the ciphertext, and on a mismatch it returns a pseudorandom "implicit rejection" key. That makes it safe against chosen ciphertexts, and it is what a real hybrid uses (X25519MLKEM768 in TLS today).
-
★ Research: where small lattice attacks stop. For LWE with q = 3329 and small secrets, find the dimension at which LLL and BKZ stop recovering s, and compare with the lattice estimator.
Where to start.
- Generate instances with n from 10 to 60, m ≈ 2n samples, and ternary secrets and errors.
- Build the primal attack's embedding lattice (Kannan's embedding of b into the q-ary lattice of A). Its unique shortest vector is (e, s, 1) up to sign.
- Reduce it with LLL. Ours works in exact rationals and is slow, so use a floating-point LLL, or
fpylll's. Then repeat with BKZ at block sizes β = 10, 20 and 30. - Record the success rate against n for each method.
- Compare with the predictions of the Lattice Estimator (Albrecht, Player and Scott 2015, and its current open-source version). The 2016 "core-SVP" model of Alkim, Ducas, Pöppelmann and Schwabe predicts the β needed from n, q and the noise.
How well do the predictions match at these small sizes, where the asymptotic heuristics are least trustworthy? Does the success curve have the sharp threshold the "2016 estimate" assumes? Published experiments (Albrecht et al., "Revisiting the expected cost of solving uSVP", 2017) are the place to begin. Extrapolating them is how every post-quantum key size is set.
Notes and sources
Glossary
公钥 public key · 私钥 private key · 密钥分配 key distribution · Merkle 谜题 Merkle's puzzles · 模运算 modular arithmetic · 扩展欧几里得算法 extended Euclidean algorithm · Bézout 等式 · 平方乘 square-and-multiply · 群 group · 生成元 generator · 阶 order · 拉格朗日定理 Lagrange's theorem · 费马小定理 Fermat's little theorem · 欧拉定理 Euler's theorem · 中国剩余定理 Chinese remainder theorem · 离散对数 discrete logarithm · Diffie–Hellman 密钥交换 · 中间人 man in the middle · RSA · 填充 padding · OAEP · 因数分解 factoring · 光滑数 smooth number · 二次筛法 quadratic sieve · 数域筛法 number field sieve · 小步大步法 baby-step giant-step · 安全素数 safe prime · 指数演算 index calculus · 椭圆曲线 elliptic curve · 无穷远点 point at infinity · 标量乘法 scalar multiplication · ECDSA · 随机数复用 nonce reuse · 证书 certificate · 证书颁发机构 certificate authority · 证书链 certificate chain · 证书透明 Certificate Transparency · 握手 handshake · 密钥派生 key derivation · 前向保密 forward secrecy · 周期寻找 period finding · 先收集后解密 harvest now, decrypt later · 格 lattice · 格基约化 lattice reduction · 带误差学习 learning with errors · 数论变换 number-theoretic transform · 混合密钥交换 hybrid key exchange · 一次性签名 one-time signature · 零知识 zero knowledge · 秘密共享 secret sharing · 多方计算 multiparty computation · 全同态加密 fully homomorphic encryption
Sources
Canon. Books:
- Katz & Lindell, Introduction to Modern Cryptography (3rd ed., 2020);
- Boneh & Shoup, A Graduate Course in Applied Cryptography (v0.6, 2023);
- Silverman, The Arithmetic of Elliptic Curves (2nd ed., 2009); Washington, Elliptic Curves: Number Theory and Cryptography (2nd ed., 2008);
- Crandall & Pomerance, Prime Numbers: A Computational Perspective (2nd ed., 2005);
- Galbraith, Mathematics of Public Key Cryptography (2012); Peikert, A Decade of Lattice Cryptography (2016).
Papers and standards:
- Key exchange and RSA: Merkle (1978); Diffie & Hellman (1976); Rivest, Shamir & Adleman (1978); Ellis (1970, 1987); Cocks (1973); Barak & Mahmoody-Ghidary (2009).
- Padding and attacks: Bellare & Rogaway (1994); Bleichenbacher (1998); Böck, Somorovsky & Young, "ROBOT" (2018).
- Factoring and logs:
- Pollard (1974, 1975, 1978); Brent (1980); Pomerance (1982); Lenstra & Lenstra (eds.), The Development of the Number Field Sieve (1993);
- Boudot et al., RSA-240 and RSA-250 (2020); Shanks (1971); Pohlig & Hellman (1978);
- Adrian et al., "Imperfect Forward Secrecy" (Logjam, 2015).
- Curves and signatures: Miller (1985); Koblitz (1987); Bernstein, "Curve25519" (2006); RFC 7748; FIPS 186-5; RFC 6979; fail0verflow, "Console Hacking 2010" (27C3); Schnorr (1991); Fiat & Shamir (1986); Lamport (1979).
- PKI and TLS:
- RFC 5280; RFC 6962 (Laurie, Langley & Kasper, Certificate Transparency);
- Fox-IT's DigiNotar report (2012); Aas et al., "Let's Encrypt" (2019);
- RFC 8446; Krawczyk, "Cryptographic Extraction and Key Derivation" (2010), RFC 5869.
- Quantum and lattices:
- Shor (1994); Gidney (2025); Lenstra, Lenstra & Lovász (1982); Shamir (1982);
- Lagarias & Odlyzko (1985); Regev (2005);
- FIPS 203, 204, 205 (2024); Alkim, Ducas, Pöppelmann & Schwabe (2016); Albrecht, Player & Scott (2015);
- Beullens (2022); Castryck & Decru (2023).
- Beyond: Shamir (1979); Yao (1986); Goldreich, Micali & Wigderson (1987); Bogetoft et al., "Secure multiparty computation goes live" (2009); Gentry (2009); Impagliazzo & Rudich (1989).
About this partfrom its README
Part 30 of a sixty-one-part course in computer science (see the series plan and the syllabus), the last part of Act V, Limits and Secrets. Two strangers can agree on a secret while everyone listens. That took Diffie and Hellman (1976), RSA (1977) and the number theory of groups. Elliptic curves made it compact, and lattices may keep it safe against a quantum computer. Two of our machines end the part by running a TLS 1.3-style handshake. Everything is built from scratch and run; the code is for learning, never for real use.
The instrument is pubkey.py. It holds:
- number theory: extended Euclid with a trace, inverses, square-and-multiply with a trace, the CRT, Miller–Rabin, generators and orders;
- Merkle's puzzles; Diffie–Hellman and its man in the middle;
- RSA:
- key generation, CRT decryption;
- OAEP with MGF1-SHA-256, and hash-and-sign;
- PKCS #1 v1.5 padding, and Bleichenbacher's attack with a trace of the shrinking interval;
- factoring: Brent's variant of Pollard's rho, the rho walk itself, and a quadratic sieve (Tonelli–Shanks roots, log sieving, linear algebra over GF(2));
- discrete logs: baby-step giant-step, Pollard's rho in a prime-order subgroup, Pohlig–Hellman, and a toy index calculus;
- elliptic curves:
- affine arithmetic, P-256, a toy curve over GF(97);
- ECDSA with RFC 6979 nonces, and nonce-reuse key recovery;
- X25519 (RFC 7748's Montgomery ladder);
- ECDSA certificates and chain verification; HKDF and TLS 1.3's labelled expansion; a TLS 1.3-shaped handshake (X25519, a certificate chain, CertificateVerify, Finished MACs and AES-128-GCM from Part 29);
- lattices:
- Gauss reduction with every step, and exact LLL;
- a Merkle–Hellman knapsack and the Lagarias–Odlyzko attack;
- Regev's LWE encryption;
- ML-KEM's ring arithmetic (FIPS 203's NTT, base multiplication and centred binomial noise), and a K-PKE with ML-KEM-512's parameters, using our own sampling instead of SHAKE and no byte encodings;
- Lamport one-time signatures; Schnorr signatures with Fiat–Shamir; Shamir secret sharing.
Each Merkle puzzle uses its own public salt in both hash checks and its pad, while its identifying number stays
encrypted. This prevents one shared weak-key lookup table from solving all puzzles. Bob's search counts and
agreement are measured; Eve's approximately n²/4 entries are an independent brute-force work model. The quadratic
barrier theorem concerns classical protocols in the ideal random-oracle model.
The RSA signature example uses a custom expanded-hash encoding for teaching, rather than standardized RSA-PSS.
RSA-OAEP checks ciphertext and encoding lengths and canonical representatives. The Bleichenbacher demonstration
uses a prefix-only 00 02 oracle, stronger than a complete PKCS #1 v1.5 padding parser. These examples do not
implement a production TLS stack or production certificate policy.
It is tested in tests/test_cs30_pubkey.py:
- X25519 against RFC 7748;
- HKDF against RFC 5869's first test case;
- P-256 ECDSA against RFC 6979 A.2.5 (the public key, and r and s for "sample"; n·G = O);
- Euclid, the CRT, Miller–Rabin (including the Carmichael number 561), generators;
- BSGS, Pohlig–Hellman and index calculus; rho and the sieve on a 20-digit semiprime;
- RSA with and without CRT, OAEP, signatures, and Bleichenbacher's attack on a 256-bit key;
- nonce-reuse recovery, and every check of the handshake;
- Gauss reduction (same covolume), the knapsack attack, the NTT against schoolbook multiplication, K-PKE and LWE round trips;
- Lamport, Schnorr and Shamir.
Outside the tests, the cryptography library (version 50) cross-checked our code:
-
it decrypted our RSA-OAEP ciphertexts, and we decrypted its;
-
it verified our ECDSA signatures;
-
its X25519 agreed with ours.
-
Two strangers, one secret. Hook.
- Diffie–Hellman with p = 23 and g = 5: A = 8, B = 19, shared secret 2.
- The same exchange in RFC 3526's 2048-bit group: 27 ms in Python.
-
1. Key distribution and Merkle's puzzles.
- n(n−1)/2 keys.
- Independently salted Merkle puzzles at n = 100, 1,000 and 10,000: measured Bob search counts and successful agreement, compared with modeled Eve work of approximately n²/4.
- GCHQ's earlier discoveries.
-
2. Modular arithmetic.
- The clock. Extended Euclid on (240, 46): 240·(−9) + 46·47 = 2.
- 17⁻¹ mod 3120 = 2753.
- 3²¹⁸ mod 1000 = 489 by eight squarings and five multiplications.
-
3. Groups and the discrete logarithm.
- Powers of 5 mod 23 visit all 22 elements. The orders are 1, 2, 11 and 22 (Lagrange); Fermat and Euler.
- 2ˣ mod 1019 as a scatter.
-
4. Diffie–Hellman. Paint; the mathematics; CDH and DDH; Mallory's two keys (15 and 8).
-
5. RSA.
- p = 61, q = 53, e = 17, d = 2753: 65 → 2790 → 65.
- The proof via Euler and the CRT.
- A 2048-bit key: the prime searches took 354, 99 and 360 candidates against the 355 expected, and the key 0.7 s. Decryption takes 29 ms, or 8.9 ms with the CRT.
- Textbook malleability; OAEP; signing.
-
6. Bleichenbacher's oracle.
- PKCS #1 v1.5 and the oracle.
- 33,392 queries for a 256-bit key and 128,789 for a 384-bit one, with the uncertainty curve. ROBOT; TLS 1.3.
-
7. Factoring.
- The rho walk mod 1009: a tail of 7 and a cycle of 14; gcd = 1009.
- Rho against our sieve from 10 to 34 digits.
- A smooth relation and a GF(2) dependency of 46 relations on a 20-digit n.
- The NFS and the factoring records.
-
8. Discrete logarithms.
- BSGS from 24 to 40 bits.
- Pohlig–Hellman on an 84-bit prime with smooth p − 1, solved in 0.6 ms, against a safe prime.
- Index calculus on a 30-bit prime: 22 primes, 37 relations. Logjam.
-
9. Elliptic curves.
- Over ℝ: (−1, 1) + (0, 1) = (1, −1), and 2·(−1, 1) = (3, −5).
- Over GF(97): 99 points and 𝒪, and a generator of order 50.
- P-256 scalar multiplication in 21 ms; key sizes; X25519 against RFC 7748.
-
10. Signatures.
- ECDSA, and RFC 6979's vector.
- Two signatures with one nonce: k and d recovered, and a forged signature that verifies; the PS3.
-
11. Certificates and trust.
- A three-certificate chain verifies; a tampered leaf and a self-signed impostor are rejected.
- DigiNotar; Certificate Transparency; Let's Encrypt.
-
12. TLS 1.3.
- The handshake between two of our machines, with message sizes; every check passes.
- The key schedule; forward secrecy.
-
13. Shor's threat.
- Periods of 7 mod 15 (r = 4 → 3·5), of 2 mod 21 and of 2 mod 35.
- Harvest now, decrypt later; FIPS 203–205; hybrids.
-
14. Lattices.
- Gauss reduction from (90, 123), (56, 76) to (−6, 3), (−2, −7).
- LLL recovers all 20 bits of a knapsack.
- LWE decryptions: 400 of 400 correct, with their noise.
- The NTT is about 12× faster than schoolbook. Our ML-KEM-512 arithmetic decrypts 25,600 bits with no errors. Lamport; SLH-DSA.
-
15. Zero knowledge, sharing and computing on secrets.
- Schnorr identification and Fiat–Shamir.
- Shamir sharing over GF(2⁶¹ − 1): any three of five shares give 31337, two give garbage.
- MPC and FHE.
-
16. Frontier: post-quantum and beyond.
- Rainbow and SIKE broken; HQC.
- The 2024 quantum-LWE claim and its retraction.
- Open problems. Outro.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Key distribution; Merkle's puzzles (a quadratic gap); Diffie–Hellman (1976); GCHQ's earlier, secret work (Ellis, Cocks, Williamson).
- The toolkit: modular arithmetic; extended Euclid and Bézout (animated); inverses; exponentiation by squaring.
- Groups: ℤ_p^* is cyclic; Fermat via Lagrange; Euler; the discrete log.
- Diffie–Hellman: paint mixing, then the mathematics; CDH and DDH; man-in-the-middle, so authentication is needed.
- RSA: key generation, correctness via CRT and Euler (proved); textbook RSA's malleability; OAEP; hash-and-sign; Bleichenbacher (1998).
- Factoring: Pollard's ρ (the birthday bound once more; the ρ shape); the quadratic sieve (smooth numbers, linear algebra over GF(2)); the number field sieve L_n[1/3]; RSA-250 (2020, cited).
- Discrete logs: baby-step giant-step; ρ; Pohlig–Hellman; index calculus.
- Elliptic curves:
- the chord-and-tangent group law over ℝ (the 3B1B-style centerpiece);
- the point cloud over F_p; scalar multiplication;
- ECDH and ECDSA; Curve25519;
- why no index calculus means smaller keys;
- nonce reuse (the 2010 PS3 key recovery, recomputed on a toy curve).
- Signatures and PKI: certificates, chains of trust, certificate transparency (Part 29's Merkle logs).
- TLS 1.3 (RFC 8446) as a sequence diagram between two simulated Pebbles: ECDHE, signatures, HKDF, AEAD; forward secrecy.
- Shor's threat (Part 53), and "harvest now, decrypt later."
- Lattices:
- bases and shortest vectors; LLL (1982), animated in 2D;
- LWE (Regev 2005) and worst-case to average-case reductions;
- ML-KEM (FIPS 203, 2024): module-LWE with the NTT (callback to Part 19);
- ML-DSA and SLH-DSA; Lamport one-time signatures and Merkle trees.
- Zero knowledge in practice: Schnorr and Fiat–Shamir (Part 27); SNARKs from polynomial commitments (KZG), sketched.
- Beyond: FHE (Gentry 2009, bootstrapping); MPC (Yao's garbled circuits; Shamir sharing, the Reed–Solomon polynomials again); differential privacy (callback to AI, Built 31). Outro.
Computed: extended-Euclid traces; 2048-bit RSA keys from our Miller–Rabin, checked; Pollard ρ timings as the semiprimes grow; BSGS; the group law over ℝ and F_p; ECDSA nonce-reuse key recovery; a TLS-like transcript; LLL breaking a toy knapsack; toy LWE and its noise; Shamir sharing. Visuals: the elliptic curve's chord, third point and reflection; the F_p cloud; lattice bases reducing; LWE's blurred lattice; the handshake. In practice: TLS certificates and Let's Encrypt, SSH keys, code signing, passkeys, the post-quantum migration. Reading: Katz & Lindell ch. 9–14; Boneh & Shoup parts II–III; Hoffstein, Pipher & Silverman, An Introduction to Mathematical Cryptography; Washington, Elliptic Curves; Silverman & Tate, Rational Points on Elliptic Curves; Shoup, A Computational Introduction to Number Theory and Algebra; Crandall & Pomerance, Prime Numbers; Diffie & Hellman 1976; Rivest, Shamir & Adleman 1978; Regev 2009; Peikert 2016; NIST FIPS 203–205 (2024); RFC 8446.
中文讲义
本讲的中文部分(与英文版对应)。
习题与解答
-
RSA 总是正确的。 用中国剩余定理证明:对 ℤ_n 中的每个 m,包括与 n 有公因子的,RSA 解密都正确。
解答
写 ed = 1 + k(p − 1)(q − 1)。先模 p:若 p ∤ m,由费马小定理 m^{p−1} ≡ 1,于是 m^{ed} = m·(m^{p−1})^{k(q−1)} ≡ m; 若 p | m,两边模 p 都是 0。所以 m^{ed} ≡ m (mod p),同理模 q 也成立。p、q 是不同的素数,由中国剩余定理,这两个同余式确定 m^{ed} 模 n = pq 的值,所以 m^{ed} ≡ m (mod n)。
-
知道太多就能分解 n。 证明对 n = pq,知道 φ(n) 就能分解 n;并证明知道 e 和 d 就能以很高的概率分解 n。
解答
由 φ(n) = n − (p + q) + 1 得 p + q = n − φ(n) + 1;又 pq = n,所以 p、q 是 x² − (n − φ + 1)x + n 的两个根。由 e 和 d:ed − 1 是 λ(n) 的倍数。写 ed − 1 = 2ᵗr,r 为奇数。随机取 a,计算 a^r, a^{2r}, …。序列会到达 1,它前面的那个值是 1 的平方根;与 Miller–Rabin 一样,对至少一半的 a,这个根不是 ±1。于是 x² ≡ 1 且 x ≢ ±1,gcd(x − 1, n) 就是 p 或 q。所以公开 d 和公开因子一样糟:丢了 d 的服务器必须更换 n,而不只是 d。
-
Pohlig–Hellman 的代价。 证明在阶为 n = ∏ qᵢ^{eᵢ} 的群中,Pohlig–Hellman 需要 O(∑ eᵢ(log n + √qᵢ)) 次群运算。
解答
对每个素数幂 qᵉ:把 g 和 h 升到 n/qᵉ 次幂,花 O(log n) 次运算,把它们投到阶为 qᵉ 的子群;然后按 q 进制一位一位地求 那里的对数。第 j 位需要一次乘幂来剥掉已求出的各位,O(log n),以及一次阶为 q 的子群中的离散对数,用小步大步法 O(√qᵢ)。一共 eᵢ 位,每位 O(log n + √qᵢ),外加投影的 O(log n)。对 i 求和,再加上可以忽略的 CRT,就得到这个界。代价由群阶的最大素因子决定, 所以群阶必须有一个至少 2²⁵⁶ 的素因子。
-
ECDSA 的脆弱。 推导随机数复用时的恢复方法,并证明只要知道单个签名的 k 就能得出 d。
解答
签名满足 s ≡ k⁻¹(z + rd) (mod n)。对哈希为 z₁、z₂ 的两条消息使用同一个 k(因而 r 相同):s₁ − s₂ ≡ k⁻¹(z₁ − z₂), 所以 k ≡ (z₁ − z₂)(s₁ − s₂)⁻¹(当 s₁ ≠ s₂ 时),然后 d ≡ (s₁k − z₁)r⁻¹。第二步只需要 k,所以只要有一个签名的随机数泄露,无论是 因为复用、糟糕的生成器还是侧信道,都会交出 d。第 10 章在 P-256 上恢复出了两者。
-
动手:混合握手。 把 TLS 式握手扩展为混合方案,X25519 加本部分的 K-PKE,并检查双方得出相同的密钥。
解答
客户端在 ClientHello 中,在 X25519 份额旁边再加一个 K-PKE 公钥。服务器随机选一个 32 字节的秘密 m,用该公钥加密它的 256 位,连同自己的 X25519 份额一起返回密文。双方计算 IKM = X25519 秘密 ‖ m(客户端解密得到 m),用它代替单独的 X25519 秘密送入 HKDF-Extract。把公钥和密文都放进记录,让 Finished MAC 和签名覆盖它们。只要解密成功,派生出的密钥就一致;第 14 章在 25,600 位中 测得没有失败。只要其中一个组成部分安全,组合就安全:X25519 对付经典攻击者,K-PKE 对付量子攻击者。一个提醒:我们的 K-PKE 只是 CPA 安全的。ML-KEM 用 Fujisaki–Okamoto 变换包装它:重新加密解出的消息并与密文比较,不一致时返回一个伪随机的「隐式拒绝」密钥。 这使它能抵御选择密文攻击,真正的混合方案(如今 TLS 中的 X25519MLKEM768)用的就是它。
-
★ 研究:小规模格攻击在哪里失效。 对 q = 3329、秘密很小的 LWE,找出 LLL 与 BKZ 不再能恢复 s 的维数,并与格估计器比较。
从哪里入手。 生成 n 从 10 到 60、约 m ≈ 2n 个样本、秘密与误差取三值的实例。构造原始攻击的嵌入格(把 b 用 Kannan 嵌入法放进 A 的 q 元格),它唯一的最短向量在正负号意义下是 (e, s, 1)。用 LLL 约化它(我们的 LLL 用精确有理数,很慢;改用浮点 LLL 或
fpylll的),再用块大小 β = 10、20、30 的 BKZ 重复,记录各方法的成功率随 n 的变化。再与格估计器(Albrecht、Player 与 Scott 2015,以及它现在的开源版本)的预测比较:Alkim、Ducas、Pöppelmann 与 Schwabe 2016 年的「core-SVP」模型由 n、q 和噪声预测所需的 β。在这些小规模下,渐近启发式最不可信,预测吻合得如何?成功率曲线是否有「2016 估计」所假设的那种陡峭阈值?已发表的实验 (Albrecht 等,《Revisiting the expected cost of solving uSVP》,2017)是起点;把它们外推,正是每个后量子密钥长度的确定方式。
Build the film
python -m videos.cs.cs30.compute # the part's numbers, into .cache/cs30
python tools/build.py cs30 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs30 Hook # one chapter, silent, with a contact sheet
Scenes: videos/cs/cs30. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.cs.cs30.compute # every number in the part (about five minutes)
python tools/build.py cs30 -q l # a 480p preview
python tools/build.py cs30 # 1080p