CComputer Science, Built

Act V · Limits and Secrets

Part 29 of 61

Secrets

Degreestarts at this level52 min of film18 chaptersprerequisites: Part 26, Part 27, Part 28

What makes a cipher secure, and what does that security rest on?

The part opens with the series' logo encrypted by AES block by block: only 85 distinct blocks appear among 768 and the logo is still visible, though nothing is wrong with AES. It then follows two thousand years in which ciphers fell to counting: a substitution cipher on 600 letters of Moby-Dick is broken by hill climbing on quadgram scores, Vigenere by the index of coincidence, and Enigma by Rejewski's observation that cycle type survives the plugboard. Shannon's theorem of 1949 ends that contest and sets the price: perfect secrecy needs as many keys as messages. The part turns there. Modern cryptography limits the attacker to polynomial time, defines security as a game with negligible advantage, and proves schemes by reduction to pseudorandom generators, functions and permutations. AES is built from inversion in the field of bytes and matches FIPS-197, and one flipped bit spreads to half the state in two rounds. The rest is how it breaks in use: ECB, a padding oracle that recovers a message in 6,412 queries, malleable counter mode, length extension, a differential attack on a toy cipher, timing leaks and a key seeded from a process ID.

What you need. Modular arithmetic, XOR, and elementary probability; the finite field of bytes from Part 28.

Mathematics, ideas and history
frequency analysis, Enigma, perfect secrecy, PRGs/PRFs, Feistel and AES, modes, MACs, hashes and sponges, cryptanalysis, side channels
What we build or compute
AES from scratch; the ECB penguin

What you will be able to do

Degree

  • Break a Caesar or Vigenere cipher by frequency counts and the index of coincidence.
  • State Shannon's perfect secrecy, and prove that it needs at least as many keys as messages.
  • Explain why reusing a one-time pad or encrypting block by block leaks the message.

Graduate

  • Define IND-CPA security as a game, and explain why a secure cipher must be randomized.
  • Build a pseudorandom function from a generator by the GGM tree, and a permutation from a function by Feistel rounds.
  • Trace one AES round on a state, and compute the birthday cost of a collision on an n-bit hash.

Research

  • State what is known about basing one-way functions on the hardness of Kolmogorov complexity (Liu-Pass).
  • Explain what Grover's and Simon's algorithms do to symmetric keys and to modes, and state the known bounds for key-alternating ciphers.

Industry

  • Choose a mode and a MAC: authenticated encryption, verified before decrypting, with a nonce that never repeats under a key.
  • Store passwords with a salted, slow, memory-hard hash, and compare tags with a fixed-work comparison.
  • Recognize a padding oracle, a length-extension forgery and a weak seed in a code review.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Degree 17 min · Graduate 50 min · Research 52 min · Industry 26 min.

  1. 0Two thousand years of secretsDegree2 min
  2. 1Substitution and frequency analysisDegree3 min
  3. 2Vigenère and the index of coincidenceDegree3 min
  4. 3EnigmaDegree4 min
  5. 4Perfect secrecyDegree3 min
  6. 5What secure meansGraduate3 min
  7. 6Pseudorandom generatorsGraduate3 min
  8. 7Pseudorandom functions and permutationsGraduate2 min
  9. 8AESGraduate2 min
  10. 9The avalancheGraduate2 min
  11. 10Modes of operationIndustry3 min
  12. 11IntegrityGraduate4 min
  13. 12Hash functionsGraduate4 min
  14. 13Hashes at workIndustry2 min
  15. 14CryptanalysisGraduate4 min
  16. 15Side channels and bad randomnessIndustry4 min
  17. 16Frontier: proofs, quanta and lightweight ciphersResearch2 min
  18. 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 thousand years of secretsDegree2 min

This is our logo: a hundred and twenty-eight by ninety-six grey pixels, one byte each. Now encrypt it with AES, the cipher that protects most of the world's traffic, with a 128-bit key. Here is the ciphertext, drawn as pixels. You can still see the logo. Nothing is wrong with AES. The image was cut into seven hundred and sixty-eight blocks of sixteen bytes, and each block was encrypted on its own, the obvious way. Equal blocks of background give equal blocks of ciphertext: only eighty-five different blocks appear, exactly as many as in the picture. The same cipher with the same key, used in a mode that chains each block to the one before, gives this: every block different. To see the difference plainly, paint each sixteen-byte block of ciphertext with a colour made from its own first three bytes. Under ECB the logo is unmistakable; chained, it is confetti. A cipher is a component. Secrecy comes from how it is used, and from proving that using it that way is safe. That is this part.

For two thousand years secret writing was a contest between the people who made ciphers and the people who broke them, and the breakers usually won. Julius Caesar shifted letters. In the ninth century al-Kindi showed how to break any such cipher by counting letters. Ciphers with many shifts held out for three hundred years, and the Enigma machine for a decade, until Polish and British mathematicians broke it, again by counting. Then in 1949 Claude Shannon proved what perfect secrecy costs: a key as long as the message itself. Modern cryptography gets around his theorem with one assumption: the attacker's computing power is limited. It builds everything on that, from the Data Encryption Standard to AES, and then attacks its own constructions as hard as it can.

1Substitution and frequency analysisDegree3 min

The oldest ciphers replace each letter by another. Caesar shifted every letter three places along the alphabet. There are only twenty-six shifts, so anyone who suspects a shift can simply try them all. A substitution cipher allows any rearrangement of the alphabet as the key. Here is one, and the opening of Moby-Dick under it. There are twenty-six factorial keys, about four times ten to the twenty-six. Trying a billion a second would take thirteen billion years, about the age of the universe. A large key space is necessary, but it is not enough. This cipher falls in seconds.

The method was written down in Baghdad in the ninth century by the philosopher al-Kindi, in a manuscript on deciphering cryptographic messages. Count how often each letter appears in the ciphertext, and compare with how often letters appear in the language. A substitution moves the bars around, but cannot change their heights. Here the commonest ciphertext letter is W, at almost thirteen percent, and the commonest English letter is E, at almost thirteen percent. W is probably E. Matching every letter by rank gives a first guess at the key. It is wrong in most places, because six hundred letters do not rank the rarer letters reliably. But it is a start, and the rest is search.

To search, we need a way to score a guess. We count every run of four letters in six million letters of other novels, and score a candidate text by how likely its own runs are. English scores high; gibberish scores low. Then climb: swap two letters of the key, and keep the swap if the score improves. Watch the text sharpen. Common short words appear first, then longer ones, and then: Call me Ishmael. Some years ago, never mind how long precisely. A climb can get stuck on a false peak, as our first attempt did, so we restart a few times from jiggled starting keys; the other five all reached the same, higher score. Six hundred letters, every one correct, in a few seconds of Python. Edgar Allan Poe knew this in 1843: a substitution cipher hides nothing from someone willing to count.

2Vigenère and the index of coincidenceDegree3 min

The defence against counting is to use many substitutions. Giovan Battista Bellaso described it in 1553, and it was later credited to Blaise de Vigenère: shift each letter by the next letter of a keyword, here BABBAGE, repeating. A shifts by zero, B by one, G by six. Now the same plaintext letter becomes different ciphertext letters. These five E's are enciphered as K, E, F, E and K. The letter counts flatten out, and al-Kindi's method has nothing to grip. It was called the indecipherable cipher, and trusted for three hundred years. Then Charles Babbage, in 1854, and Friedrich Kasiski, in 1863, saw the weakness: once you know the length of the keyword, the cipher falls apart into simple shifts.

William Friedman gave the test its modern form in 1922. The index of coincidence is the chance that two letters picked at random from a text are the same. English is lumpy, with many E's and T's, so it scores about six and a half percent; letters spread evenly score one in twenty-six, under four percent. Our whole ciphertext scores four and a half: close to random, as the cipher intends. Now guess a key length, and split the ciphertext into that many columns: every first letter, every second letter, and so on. If the guess is right, each column was shifted by a single letter, and its index jumps back up to English. Try every length from one to twenty. Seven stands out, and fourteen, its double. The key has seven letters.

With the length known, each column is a Caesar cipher. For the first column, try all twenty-six shifts and measure how far each result's letter counts are from English. One shift, B, fits far better than any other. Repeat for each of the seven columns, and the keyword reads itself off: BABBAGE. All six hundred letters decrypt. The lesson outlives the cipher. A short key used over and over leaves patterns in the ciphertext, and statistics will find them. Every cipher in this part either uses its key once, like Shannon's, or stretches it into something that never repeats.

3EnigmaDegree4 min

Enigma, patented by Arthur Scherbius in 1918 and used by every branch of the German military, mechanised Vigenère's idea. Pressing a key sends a current through a plugboard, then through three rotors, each a fixed wiring of the twenty-six letters: a permutation. A reflector sends it back through the rotors and plugboard to light a lamp. Before each letter the right rotor steps, and now and then the others, so every letter is enciphered by a different permutation. Our simulation passes the standard test, and enciphers a weather report. The reflector has two consequences: enciphering the ciphertext again gives back the message, and no letter is ever enciphered as itself. Look down the columns: never the same letter. The plugboard's ten cables could be placed in a hundred and fifty million million ways. With the choice and order of three rotors from five and their starting positions, an operator chose each day among a hundred and fifty-nine billion billion keys.

The first break came from mathematics. Marian Rejewski, a young Polish mathematician, worked on Enigma in 1932. Operators began each message with a three-letter message key, enciphered twice for safety. So the first and fourth letters were the same letter under two different permutations, and from a day's worth of messages Rejewski could reconstruct the product of the two: a permutation of the alphabet. Here is that product for one setting of our simulated rotors, written as cycles: A goes to I, I to D, and so on, two cycles of thirteen. Now add ten plugboard cables. The letters in the cycles change completely; the lengths of the cycles do not. That is a theorem from group theory: the plugboard S is applied on the way in and on the way out, so it conjugates the product, and conjugation renames letters without changing the shape of the cycles. So the cycle lengths, the day's characteristic, depend only on the rotors. A different setting gives a different shape. The Poles built a device to catalogue the characteristic of every rotor setting, a hundred thousand of them, and then found each day's setting by looking it up, ignoring the plugboard's hundred and fifty million million possibilities entirely.

In 1939, weeks before the war, the Poles gave everything they had to the British and French. At Bletchley Park the work moved from mathematics to machinery. The British relied on cribs: words a message probably contained. Weather stations sent weather reports, in a fixed format, every day. To place a crib, slide it along the ciphertext. Wherever a crib letter lines up with the same ciphertext letter, that position is impossible, because Enigma never enciphers a letter as itself. On our message, nine of the fifteen positions are ruled out at once. Alan Turing, with Gordon Welchman, designed the Bombe: an electrical machine that took a placed crib and ran through rotor settings, rejecting every one that led to a contradiction. By the end of the war over two hundred Bombes were running, and the Colossus machines, the first programmable electronic computers, were breaking a different German cipher, the Lorenz teleprinter. The reflector's elegant symmetry was the machine's weakness.

4Perfect secrecyDegree3 min

Is there a cipher no amount of cleverness can break? In 1917 Gilbert Vernam, at AT and T, combined each bit of a teleprinter message with a bit of a random key tape: exclusive or. Here is HI, sixteen bits, a key, and the ciphertext. Use the key once, and never again. In 1949 Shannon made secrecy precise. A cipher is perfectly secret if seeing the ciphertext does not change the probability of any message: what an attacker believes afterwards is what they believed before. The pad meets it. For two bits, look at the table: each row, one message, contains every ciphertext exactly once. So any ciphertext comes from any message under exactly one key, and with a uniform key every ciphertext is equally likely whatever the message was. Not hard to break: impossible. No computer, no amount of time, no quantum machine helps.

Shannon also proved the catch, and the proof is three lines. Take any ciphertext, and decrypt it under every possible key. You get at most one message per key. If there are fewer keys than messages, some message is missing from that list: given this ciphertext, its probability is zero. But before the ciphertext arrived, it was possible. Seeing the ciphertext changed what the attacker believes, so the cipher is not perfectly secret. Perfect secrecy needs at least as many keys as messages, so a key as long as everything you will ever send. And that key must reach the other side in secret. If you have a secure way to send a key that long, you could have sent the message instead.

And the pad must be used once. Encrypt two messages with the same key, and an eavesdropper who XORs the two ciphertexts gets the XOR of the two messages: the key cancels out. That is not yet either message, but English is redundant. Guess a common word, space T H E space, at some position in one message; XOR it in, and you read what the other message says there. Slide it along. At three offsets the result is English: code, under, and bridge. Each hit reveals a piece of both messages, and each piece suggests the next guess. This happened. In 1942 a Soviet factory under wartime pressure printed some pad pages twice. American codebreakers in the VENONA project noticed, and over the following decades read parts of about three thousand messages, exposing atomic spies. The pad's perfection has three conditions, and every one is fragile: random, secret, once.

5What secure meansGraduate3 min

Shannon's theorem is final: with keys shorter than messages, a ciphertext always leaks something to an attacker with unlimited time. So modern cryptography limits the attacker. First, a rule from Auguste Kerckhoffs in 1883: assume the enemy knows how your system works. Only the key is secret, because algorithms leak, get published, get stolen. Second, the attacker is an efficient algorithm: one that may flip coins, and runs in time polynomial in the key length. Third, its advantage over blind guessing must be negligible: smaller than one over any polynomial, like two to the minus n. In concrete numbers: trying every key of DES took a special machine fifty-six hours in 1998. Every Bitcoin miner together computes about two to the ninety-four hashes a year. Two to the hundred and twenty-eight is seventeen billion times more. That is the margin AES is built to.

What should the attacker be unable to do? Shafi Goldwasser and Silvio Micali answered in 1982 with a game. A challenger holds a secret key. The adversary may ask for the encryption of any messages it likes: chosen plaintexts. Then it hands over two messages of its choice. The challenger secretly flips a coin and returns the encryption of one of them. The adversary may ask more questions, and finally guesses which one it got. The scheme is secure if no efficient adversary guesses right noticeably more than half the time. If you cannot even tell which of two messages you chose was encrypted, you learn nothing useful about any message: Goldwasser and Micali proved this equivalent to semantic security, and it won them the Turing Award. One consequence is immediate. If encryption is deterministic, the adversary simply asks for the encryption of m-zero in advance and compares. Secure encryption must use fresh randomness in this stateless game. A stateful scheme can instead manage unique nonces, with a security definition that enforces the nonce rules. CBC needs unpredictable IVs; CTR needs nonrepeating counters under each key.

How do you prove a scheme wins this game? Not directly: nobody knows how. Instead, by reduction, the method of Part 26. Suppose some adversary A breaks the scheme. Build a new algorithm B that attacks a simpler primitive, say a pseudorandom generator, by running A inside it, simulating the scheme for A with the primitive it was handed. If A wins with some advantage, B wins with nearly as much. So if the primitive is secure, the scheme is. Why not prove the primitive secure too? Because a proof that any efficient algorithm fails against it would separate P from NP. So cryptography is a tower: schemes reduced to primitives, primitives reduced to a few hard problems, and the hard problems attacked by everyone, for decades. The next two chapters build the primitives.

6Pseudorandom generatorsGraduate3 min

Shannon needs a key as long as the message. A pseudorandom generator makes a short key look long. It is an efficient function G that stretches a random seed of n bits into more bits. The requirement: no efficient test, given a string, can tell whether it came from G with a random seed, or was truly random, with more than negligible advantage. Then XOR the message with G of the key. If an attacker could learn anything about the message from this ciphertext, we could turn that attacker into a test that tells G's output from random. So the cipher is as secure as the generator. Andrew Yao showed in 1982 that passing every test is the same as one simple property: nobody can predict the next bit from the bits before it. And by 1999, pseudorandom generators had been built from any one-way function at all: any function easy to compute and hard to invert.

Passing statistical tests is not enough; the definition says every efficient test. Here is the linear feedback shift register of Part 5: seventeen bits, with a feedback polynomial chosen so its period is the maximum, a hundred and thirty-one thousand bits. Its output is balanced and looks random. But every bit is a fixed XOR of earlier bits. Part 28's Berlekamp-Massey algorithm, run over the two-element field, finds the shortest register that produces any sequence, from twice its length. Given these thirty-four bits, it returns the feedback polynomial, and from there every later bit: all two thousand predicted, no errors. As a keystream, this is useless. Real designs add nonlinearity. GSM phones combined three registers with irregular clocking, and that was broken too, eventually in real time with precomputed tables.

What is used in practice? Daniel Bernstein's ChaCha20, from 2008. Its state is a four by four grid of thirty-two-bit words: four constants, eight words of key, a block counter, and a nonce, a number used once per message. The whole cipher is one small function, the quarter-round, using only three operations: add, rotate, XOR. Twenty rounds apply it to each column, then to each diagonal, so that every word soon depends on every other. Add the starting grid back in, and you have sixty-four bytes of keystream; increment the counter for the next sixty-four. Our implementation matches the standard's test vectors. It manages about seven hundred kilobytes a second in Python; vectorised C runs at gigabytes per second. With no lookup tables and no branches that depend on secrets, it leaks nothing through timing. It encrypts TLS 1.3, WireGuard and SSH connections, and generates Linux's random numbers.

7Pseudorandom functions and permutationsGraduate2 min

A generator gives one long random-looking string. Often we need more: a function that gives a random-looking answer for any input we ask about, the same answer each time. A pseudorandom function is a keyed function that no efficient attacker can tell from a truly random one, even choosing the inputs. Oded Goldreich, Shafi Goldwasser and Silvio Micali built one from any generator in 1986. Take a generator that doubles its input, and split the output into a left half and a right half. Start from the key at the root, and walk down a tree, following the bits of the input: zero means take the left half, one the right. With SHA-256 as the generator, input one, zero, one leads here, and this leaf is the output. The proof is a hybrid argument. Replace the top level with true randomness; then the next; and so on, one level at a time. If any step could be noticed, that would break the generator. After n steps the function is truly random.

A block cipher must be a permutation: every ciphertext must decrypt to one plaintext. A random-looking function need not be invertible. Horst Feistel, at IBM, found the bridge. Split the block into halves. The right half goes through any function f, the result is XORed into the left half, and the halves swap. Whatever f is, the round can be undone: you know R, so you can compute f of R again and XOR it back off. How many rounds make it look random? Two are not enough. Feed in two inputs with the same right half: the left halves of the outputs always differ by exactly the difference of the inputs. Our test catches one and two rounds every time. Michael Luby and Charles Rackoff proved in 1988 that three rounds with pseudorandom round functions give a pseudorandom permutation, and four give one that stays secure even when the attacker can also ask for decryptions. On three rounds, our test never fires. The Data Encryption Standard of 1977 is sixteen Feistel rounds.

8AESGraduate2 min

The Advanced Encryption Standard. AES works on a four by four grid of bytes, the state, filled column by column. Here is the example from the standard, after the key has been XORed in. A round has four steps. SubBytes replaces every byte by its S-box value. The S-box is the field of bytes from Part 28: take the byte's inverse in the field, then apply a fixed affine map. Fifty-three, inverted, is C A, and comes out as E D. Inversion is what makes AES nonlinear, and it was chosen because it is as far from linear as a function on bytes can be. ShiftRows rotates row one by one place, row two by two, row three by three. MixColumns multiplies each column by a fixed matrix over the same field. The matrix is maximum distance separable, the property of Reed-Solomon codes: change one byte of a column and all four output bytes change. Finally XOR the round key, derived from the cipher key by a small schedule. Substitution confuses; shifting and mixing diffuse.

Now run all ten rounds. Here is the state after each one. Within two rounds, every byte depends on every byte of the input and the key. The last round leaves out MixColumns, which makes decryption, the inverse steps in reverse order, the same shape as encryption. After round ten: sixty-nine, C four, E zero, D eight. The standard's appendix gives the same sixteen bytes. Our AES also matches the standard's second example, and decrypts what it encrypts. This is code for learning. Never use it, or anything like it, for real: it is slow, and as chapter fifteen shows, its table lookups leak the key through timing. Since 2010 most processors have had AES instructions, one round per instruction, at about a byte per clock cycle.

9The avalancheGraduate2 min

How quickly does AES forget where a change came from? Encrypt two plaintexts that differ in a single bit, under the same key, and after each round light up the state bits that differ. At the start, one bit. After round one, the S-box has turned that one bit into several bits of its byte, and MixColumns has spread them over the whole column: four bytes, seventeen bits. In round two, ShiftRows sends those four bytes to four different columns, and MixColumns spreads each again: all sixteen bytes. After that, about half the bits differ, and in no visible pattern. Horst Feistel called this the avalanche: a small change in the input should change the output completely.

If two rounds already diffuse everything, why ten? Because diffusion is not security. The best attacks on AES-128 with fewer rounds, using impossible differentials and meet-in-the-middle ideas, reach seven rounds, needing vast amounts of data and time. The last three rounds are a margin. On the full cipher, the best known key recovery, the biclique attack of 2011, needs two to the one hundred and twenty-six point one operations: four times faster than trying every key, and still impossible. Designers set the number of rounds from the best attack they know, plus a margin. Faster designs are mostly older designs with rounds removed. And there is no proof that AES is a pseudorandom permutation. Its security rests on twenty-five years of the world's cryptanalysts failing, which is how block ciphers have always earned trust.

10Modes of operationIndustry3 min

A block cipher encrypts sixteen bytes. A mode of operation says how to encrypt a message of any length. The obvious mode, electronic codebook, encrypts each block on its own. It is deterministic, so by chapter five it cannot be secure, and our logo shows why: the eighty-five distinct blocks of the picture become eighty-five distinct blocks of ciphertext, in the same places. Cipher block chaining, from 1976, XORs each plaintext block with the previous ciphertext block before encrypting, starting from a random initial value. Now every block is different. Counter mode encrypts a nonce followed by a block counter and XORs the result into the plaintext. It turns the block cipher into a stream cipher, like chapter six's: blocks can be done in parallel, or any one decrypted alone. Its one rule is absolute. Never encrypt two messages under one key with the same nonce, or you have made a two-time pad.

CBC has its own trap, and it shows how a single bit of leaked information can unravel everything. Messages are padded to a whole number of blocks; the usual rule fills the last block with n bytes, each of value n. Decryption of a block is the block cipher's inverse, XORed with the previous ciphertext block. So whatever the attacker XORs into the previous block appears, bit for bit, in the decrypted plaintext. Now suppose the server decrypts, checks the padding, and reports a padding error differently from any other error, by message or just by timing. The attacker sends a doctored previous block, changing its last byte by a guess. The padding is valid only when the plaintext's last byte has become one, and that happens exactly when the guess was right. At most two hundred and fifty-six tries reveal one byte; then the attacker aims for two twos, then three threes, working right to left. Serge Vaudenay described it in 2002, and versions of it broke SSL and TLS more than once in the following decade.

We built the server and ran the attack. Three blocks of ciphertext, encrypted under AES with a key the attacker never sees. Each query asks only: is the padding valid? Watch the plaintext appear, byte by byte, from the right of each block. It reads: PIN equals four nine two one; transfer approved by the bank. Six thousand four hundred and twelve queries, about a hundred and thirty-four per byte, two seconds. Recovering the key instead would take two to the hundred and twenty-eight tries. AES was never attacked at all. The flaw is decrypting data before checking that it is genuine. The fix is integrity, which is the next chapter.

11IntegrityGraduate4 min

Encryption keeps a message secret. It does not keep it intact. Here is a payment instruction, encrypted in counter mode. The attacker cannot read it, but suppose they know its format. Counter mode XORs a keystream into the message, so XORing something into the ciphertext XORs the same thing into the plaintext. The attacker XORs in the difference between zero zero one zero and nine nine one zero, at the right position. The receiver decrypts and pays Alice nine thousand nine hundred and ten dollars instead of ten. No key was needed. Counter mode, CBC and the one-time pad are all malleable like this. Protection needs a different tool: a message authentication code. The sender attaches a tag computed with a key, and the requirement is that without the key nobody can produce a valid tag for any message they have not seen tagged, even after seeing many.

The first MACs were built from block ciphers. CBC-MAC runs CBC encryption with a zero starting value and keeps only the last block as the tag. For messages of one fixed length, it is provably secure if the cipher is a pseudorandom permutation. But allow different lengths, and here is what an attacker can do with two tagged one-block messages. Append to the first message the second message XORed with the first tag. Running the chain, the first tag cancels, and the chain is back to encrypting the second message alone: the tag of the new, two-block message is the second tag. Our forgery verifies. Prefixing the length fixes it; the standard mode, CMAC, fixes it by treating the last block specially. The other standard is HMAC, from 1996: hash the key with the message, then hash the key with that result. It supports variable-length messages under appropriate assumptions on the hash construction, and is widely used for web APIs' signed requests and tokens.

Combine encryption and a MAC, and in which order? Mihir Bellare and Chanathip Namprempre proved a composition theorem in 2000: combine IND-CPA encryption and a strongly unforgeable MAC with independent keys. Authenticate the complete ciphertext, including its IV, then verify the tag before decrypting. Other orders can fail, as the padding oracle illustrated. Receivers check the tag first and never decrypt a forgery. Modern modes do both at once: authenticated encryption. Galois counter mode, GCM, encrypts in counter mode and computes its tag with a polynomial: the ciphertext blocks are the coefficients, evaluated at a secret point H of the field with two to the one hundred and twenty-eight elements. Part 28's algebra again. TLS 1.3 allows only modes like this. Ours matches the standard's test vectors. The polynomial makes nonces critical. Two messages tagged with the same nonce give an equation whose roots include H, and additional transcripts or attempts can resolve candidates and enable forgeries. A 2016 survey found a hundred and eighty-four HTTPS servers repeating GCM nonces. ChaCha20 pairs with Poly1305, the same idea with a polynomial modulo the prime two to the hundred and thirty minus five.

12Hash functionsGraduate4 min

A hash function squeezes any input to a short fixed-length output: SHA-256 gives two hundred and fifty-six bits. The central property is collision resistance: nobody can find two different inputs with the same hash. Since there are infinitely many inputs, collisions exist; they must just be impossible to find. There is always a generic attack: hash random inputs until two outputs match. By Part 17's birthday paradox, that takes about the square root of the number of possible outputs: two to the n over two. We cut SHA-256 down to sixteen, twenty, up to thirty-two bits and searched for collisions. The averages sit on the prediction. So a two-hundred-and-fifty-six-bit hash offers a hundred and twenty-eight bits of security against collisions, matching AES-128.

Real hash functions have broken, and it took years each time to stop using them. MD5, from 1992, has a hundred-and-twenty-eight-bit output, so the birthday attack needs two to the sixty-four. In 2004 Wang Xiaoyun and her colleagues found collisions using its internal structure; today a laptop finds one in seconds. In 2008 researchers used MD5 collisions to create a rogue certificate authority, and in 2012 the Flame malware used the same idea to forge a Microsoft code-signing certificate. SHA-1 fell in 2017: two different PDF files with the same hash, after two to the sixty-three operations. By 2020, any two chosen documents could be made to collide for about forty-five thousand dollars of computing. No attack is known on SHA-256 or SHA-3. But the lesson is agility: build systems that can change their hash function before it breaks, not after.

How are hashes like SHA-256 built? Ralph Merkle and Ivan Damgård showed in 1989 how to hash any length with a compression function f that takes a fixed-size state and one block. Chain it: pad the message with its length, feed the blocks through f one by one, and output the final state. If f resists collisions, so does the chain. But the output is the chain's whole state, so anyone holding a hash can keep going. Suppose a server authenticates requests with the hash of a secret key followed by the message. We see a request and its tag. Without knowing the secret, we append the padding the server would have added, then role equals admin, and continue the chain from the tag. The server accepts our forged tag. This broke Flickr's API in 2009, and it is exactly why HMAC exists.

When SHA-1 began to crack, the US standards institute ran another open contest, and in 2012 chose Keccak, by Guido Bertoni, Joan Daemen, Michaël Peeters and Gilles Van Assche, as SHA-3. It is built differently. The state is sixteen hundred bits, scrambled by one fixed permutation f. The state is split into a rate and a capacity. To absorb the message, XOR each block into the rate part and apply f. To squeeze out the hash, read the rate part, apply f, and read again, as much as you need. The capacity part is never output and never directly touched by the message. That hidden half is the security: an attacker cannot continue the computation from an output, so length extension is impossible. Our SHA-3, like our SHA-256, matches Python's library on every test. Ours is pure Python, the library's is optimised C, which is the difference in speed.

13Hashes at workIndustry2 min

Collision resistance turns a hash into a commitment: whoever publishes a hash is bound to the data behind it. Ralph Merkle's trees, from 1979, extend this to many items. Hash each item; then hash the hashes in pairs; and so on up to a single root. The root fixes every item below it: changing any one would change the root, unless you can find a collision. Now a server holding the tree can prove that one item, the commit that fixed an overflow, is in it, by sending only the three sibling hashes along its path. The verifier, who knows only the root, rehashes upward and compares. The proof is the logarithm of the number of items. Ours verifies; change one character of the commit, and the rebuilt root no longer matches. This structure is everywhere later in the series: git names every commit by such a hash, Certificate Transparency logs every web certificate in one, file systems like ZFS checksum every block with one, and blockchains chain them.

Hashes also guard passwords, and here the danger is not a clever attack but a fast one. A server should never store passwords, only a random salt and a deliberately slow hash of the salt and password. The salt means each guess must be hashed separately for each user, and makes precomputed tables useless. In 2012 LinkedIn lost six and a half million unsalted SHA-1 hashes, and most were cracked. Slowness is a dial. We measured: one SHA-256 takes under half a microsecond, so every lowercase eight-letter password can be tried in about a day on one core. PBKDF2, which iterates a hash six hundred thousand times as current guidance recommends, takes a sixth of a second per guess: imperceptible at login, and over a thousand years for that search. But attackers use graphics cards with thousands of cores. Memory-hard functions, scrypt and the competition winner Argon2, need megabytes of memory per guess, which those cores do not have. Use one.

14CryptanalysisGraduate4 min

How are ciphers like AES attacked, and how are they designed to resist? We use a teaching cipher by Howard Heys, small enough to break. Sixteen bits, four rounds, each a key XOR, four four-bit S-boxes, and a permutation of the wires. Eli Biham and Adi Shamir's differential cryptanalysis, published in 1990, follows not values but differences: pairs of inputs that differ by a fixed XOR. The key XOR leaves a difference unchanged. Only the S-boxes change it, and not uniformly: this table counts, for each input difference, how often each output difference occurs. Input difference B gives output difference two in eight of the sixteen cases. Chain likely cells through three rounds, following the wires, and you have a trail: a difference that survives with probability eight sixteenths, times six sixteenths, times six sixteenths squared. Twenty-seven in a thousand and twenty-four. Of five thousand chosen pairs, about a hundred and thirty should follow it all the way to the last round.

Now the attack. We encrypt five thousand pairs of chosen plaintexts with that input difference, under an unknown key. The trail predicts the difference just before the last S-boxes. Guess the eight key bits that feed the two active S-boxes; undo those S-boxes on both ciphertexts; and count how many pairs show the predicted difference. For the right guess, the trail's pairs show up: a hundred and forty-six, against the hundred and thirty-two expected. Wrong guesses see only chance: the best wrong one gets eighty. A third of a second, and eight key bits are known; the rest of the key follows the same way. IBM's designers knew this technique in 1974, as Don Coppersmith revealed twenty years later, and chose DES's S-boxes to resist it. Mitsuru Matsui's linear cryptanalysis tracks biased XORs of bits instead of differences, and broke DES with two to the forty-three known plaintexts. AES was designed with proofs against both: its mixing guarantees at least twenty-five active S-boxes in any four-round trail, so no trail is likelier than two to the minus one hundred and fifty.

One more attack, on a tempting idea. If one key is too short, encrypt twice with two keys. With our toy cipher's sixteen-bit keys, does that make a thirty-two-bit key? No. Given a plaintext and its ciphertext, encrypt the plaintext under every first key and store the results. Then decrypt the ciphertext under every second key, and look each result up. Where they match, the two halves meet in the middle. Whitfield Diffie and Martin Hellman pointed this out in 1977: a hundred and thirty-one thousand cipher calls instead of four billion. With a second plaintext pair, two candidate key pairs survive: the true one, and one impostor that happens to fit both. A third pair would settle it. So double DES is barely stronger than DES, which is why the banks' long-lived workaround was triple DES, at about a hundred and twelve bits of security, finally retired by the standards institute in 2023.

15Side channels and bad randomnessIndustry4 min

Everything so far attacked the mathematics. Real systems also leak through how long they take, how much power they draw, what they leave in the cache. Here is the obvious way to check a MAC tag: compare byte by byte, and stop at the first difference. We timed it against guesses with more correct leading bytes. The measured times depend on this machine and Python runtime. If an attacker can distinguish prefix lengths reliably, it can guess one byte at a time: roughly sixteen times two hundred and fifty-six candidate guesses. Real timing attacks generally require repeated measurements and statistical analysis, not one query per guess. The second loop visits every pair of bytes, ORs the XORs, and decides at the end. Kocher's 1996 work demonstrated timing attacks on RSA and Diffie-Hellman. For tag comparisons use the standard hmac.compare_digest implementation.

Timing leaks through memory too. Fast software AES replaces the S-box and MixColumns with lookups in four tables of a kilobyte each, indexed by bytes of the plaintext XORed with the key. A kilobyte is sixteen cache lines, Part 9's unit. An attacker running on the same machine fills the cache with its own data, lets AES run, then times its own accesses: the line AES used is now slow for the attacker, because AES evicted it. Which line was used reveals the top four bits of the plaintext byte XOR the key byte. With known plaintexts, that is half of every key byte, and later rounds give the rest. Daniel Bernstein, and then Dag Arne Osvik, Adi Shamir and Eran Tromer, recovered full AES keys this way across process boundaries in 2005 and 2006, the same mechanism Spectre would exploit in 2018. The fixes: hardware AES instructions, or bitsliced code that touches the same addresses whatever the key. And power analysis reads keys from smart cards through their power consumption, one trace at a time.

The last failure is the most basic: the key was never random. In 2006 a Debian maintainer, silencing a warning from a memory-checking tool, removed a line from OpenSSL that mixed entropy into its random number generator. What remained was the process ID: at most thirty-two thousand seven hundred and sixty-seven values. For two years, every SSH key and certificate generated on Debian and Ubuntu came from a short list, and attackers simply generated the whole list. Here is the same mistake in miniature: a hundred-and-twenty-eight-bit AES key, seeded from a process ID. We tried every ID in turn, and found the key after twenty-three thousand tries. The measured runtime is displayed. A hundred and twenty-eight bits of key, fifteen bits of randomness. And randomness can be sabotaged deliberately. Dual EC DRBG, a generator standardised in 2006, used two elliptic-curve constants of unexplained origin; whoever knew the relation between them could predict its output. It was withdrawn in 2014. The rule: take random numbers from the operating system's generator, which collects real entropy and runs it through a cipher like ChaCha20, and nowhere else.

16Frontier: proofs, quanta and lightweight ciphersResearch2 min

The theory in this part has a remarkable shape. From any one-way function, a function easy to compute and hard to invert, you can build pseudorandom generators, pseudorandom functions and permutations, secure encryption and MACs, commitments, even digital signatures. And each of these gives back a one-way function. Russell Impagliazzo called this world Minicrypt: all of symmetric cryptography stands or falls with one assumption. But one-way functions imply that P is not NP, so a proof that they exist would settle Part 26's question, and more. In 2020 Yanyi Liu and Rafael Pass found an unexpected equivalent: one-way functions exist exactly when a problem about the compressibility of strings, time-bounded Kolmogorov complexity, is mildly hard on average. Cryptography and the theory of information turned out to be one question. Meanwhile the ciphers we actually use are not built from one-way functions at all. AES is conjectured to be a pseudorandom permutation, and the only evidence is that no one has broken it.

Public-key cryptography falls to a large quantum computer, as Part 30 explains. Symmetric cryptography fares better. Lov Grover's algorithm, which Part 53 builds, searches two to the k keys in about two to the k over two quantum steps: a square root. But those steps must run one after another. Spreading the search over many machines helps only by the square root of their number, and each step needs error-corrected quantum hardware. So AES-128 is still judged adequate by the standards bodies, and AES-256 is the conservative choice for secrets that must last decades. A stranger threat came from Daniel Simon's algorithm, which finds hidden periods. From 2010 on, researchers used it to break the three-round Feistel network, the Even-Mansour cipher, CBC-MAC and GCM's authentication in polynomial time. The catch: the attacker must be able to run the keyed cipher on a superposition of inputs, which a remote server never allows. Which designs survive even that, and what a real quantum attack would cost, are active questions.

Recap, problems, and where this comes backAll tracks3 min

What we built in this part. Substitution ciphers broken by counting and climbing, and Vigenère by the index of coincidence. Enigma, simulated, and Rejewski's theorem that the plugboard cannot hide the cycle structure. Shannon's perfect secrecy and its price. Pseudorandom generators, functions and permutations, with Feistel's networks. AES from scratch, matching the standard, its avalanche, and the modes and MACs that make it safe, with the padding oracle that shows why. And hash functions, the birthday bound, and the attacks: differential, timing, and a key that was never random.

Where this comes back. Part 30 adds public keys, and two of our machines then run a TLS 1.3 handshake using this part's authenticated encryption and HMAC; its certificates are logged in Merkle trees. Part 34's file systems checksum every block with a Merkle tree. Part 38's blockchains are hash chains. Part 41's git names every object by its hash. And Part 55 returns to passwords, one-time codes built from HMAC, and passkeys.

In practice. Never invent a cipher, a mode or a protocol; use TLS, a library like libsodium, or your platform's authenticated encryption. Never reuse a nonce, and if you cannot guarantee that, use a mode designed to survive it. Store passwords with Argon2 or scrypt and a salt per user. Sign tokens with HMAC and compare tags in constant time. And take randomness only from the operating system.

Six problems, with full solutions in the part's notes. Pause on any of them. The fifth is a build problem: attack your own server, then fix it. The last, marked with a star, is a research problem: how much trails cluster as rounds grow is not known even for this toy cipher's larger relatives, and the notes say where to start.

Next time: public keys. Everything in this part assumed the two sides already share a key. Part 30 shows how two strangers can agree on one while everyone listens: Diffie and Hellman's exchange, RSA built from scratch, elliptic curves, and a full TLS handshake between two of our machines, ending with the lattices meant to survive a quantum computer. Part 30, Public Keys.

The books and papers this part follows are on screen and in the notes. Thank you for watching.

Where it goes next. Part 30 adds public keys, and two Pebbles run a TLS 1.3 handshake with this part's authenticated encryption and HMAC. Merkle trees return in the file systems of Part 34, the blockchains of Part 38 and the git objects of Part 41, and Part 55 returns to passwords, one-time codes built from HMAC, and passkeys.

Key results

The part's results in one place, for revision.

Index of coincidence\(\displaystyle \mathrm{IC}=\frac{\sum_i n_i(n_i-1)}{N(N-1)}:\ \ \text{English }0.062,\ \text{random }0.038\)
Perfect secrecy\(\displaystyle \Pr[M=m\mid C=c]=\Pr[M=m]\ \Longrightarrow\ |\mathcal K|\ge|\mathcal M|\)
IND-CPA\(\displaystyle \bigl|\Pr[\mathcal A\text{ guesses }b]-\tfrac12\bigr|\le\operatorname{negl}(n)\ \text{ for }\allowbreak \text{every }\allowbreak \text{efficient }\mathcal A\)
Switching lemma\(\displaystyle \bigl|\mathrm{Adv}^{\mathrm{PRP}}-\mathrm{Adv}^{\mathrm{PRF}}\bigr|\le\frac{q^2}{2^{\,n+1}}\)
Birthday collisions\(\displaystyle \mathbb{E}[\text{hashes }\allowbreak \text{until }\allowbreak \text{a }\allowbreak \text{collision}]\approx\sqrt{\pi/2}\;2^{\,n/2}\)
Meet in the middle\(\displaystyle \text{double }\allowbreak \text{encryption }\allowbreak \text{costs }\allowbreak \text{about }2^{\,k+1}\text{ cipher }\allowbreak \text{calls, }\allowbreak \text{not }2^{2k}\)

Try it

Lab 29 · AES from scratch: the standard's vector, the avalanche, ECB, and the birthday bound

Check the series' AES-128 against the FIPS-197 example, flip one plaintext bit and count how many of the 128 state bits differ after each round, count distinct ciphertext blocks of a striped image under ECB and CBC, and compare the number of hashes needed for a collision on truncated SHA-256 with sqrt(pi/2) 2^(n/2).

Figure produced by Lab 29: AES from scratch: the standard's vector, the avalanche, ECB, and the birthday bound
Produced by the lab below, seed 0, in 0.3 s.
python -m videos.cs.labs 29 needs numpy, scipy, matplotlib · download lab29.py · source on GitHub
AES-128 on the FIPS-197 example      69c4e0d86a7b0430d8cdb78070b4c55a   (the standard: 69c4e0d8...b4c55a)
bits differing after rounds 0, 1, 2  1.0, 15.7, 64.7   (the film: 1, 16.1, 64.4)
after ten rounds                     mean 63.9, s.d. 5.60   (Binomial(128, 1/2): 64, 5.66)
image of 192 blocks, 4 distinct      ECB: 4 distinct ciphertext blocks   CBC: 192
collision on 8 bits                  22 hashes on average   sqrt(pi/2) 2^(n/2) = 20
collision on 12 bits                 80 hashes on average   sqrt(pi/2) 2^(n/2) = 80
collision on 16 bits                 323 hashes on average   sqrt(pi/2) 2^(n/2) = 321
collision on 20 bits                 1156 hashes on average   sqrt(pi/2) 2^(n/2) = 1283

Two rounds of AES spread one bit over the whole state, and an n-bit hash resists collisions for only about 2^(n/2) tries; the cipher is sound, and the ECB leak comes from how it is used.
The code (81 lines; it asserts its own result)
"""Lab 29: run AES-128 from scratch, watch one flipped bit spread round by round, and find hash collisions at the birthday rate."""

from videos.coursekit import labs

import random

import numpy as np

from explainer.cs.algo import crypto as K

TITLE = "AES from scratch: the standard's vector, the avalanche, ECB, and the birthday bound"
GOAL = ("Check the series' AES-128 against the FIPS-197 example, flip one plaintext bit and count how many of the 128 "
        "state bits differ after each round, count distinct ciphertext blocks of a striped image under ECB and CBC, and "
        "compare the number of hashes needed for a collision on truncated SHA-256 with sqrt(pi/2) 2^(n/2).")
TASKS = [
    "Stop AES after 1, 2 and 3 rounds (rounds=) and count how many of the 16 bytes a one-bit change has reached. Why does full diffusion take two rounds?",
    "Encrypt the striped image in CTR mode with K.ctr_encrypt, then flip one ciphertext bit and decrypt. Which plaintext bits change, and what does that say about integrity?",
    "Run the birthday experiment at 24 bits. How many hashes do you predict, and how many would a 256-bit hash need?",
]
TRIALS = 150
BITS = (8, 12, 16, 20)


def run(seed=0):
    rng = random.Random(int(np.random.default_rng(seed).integers(2 ** 31)))
    lab = labs.Lab()

    # 1. the standard's example (FIPS-197, Appendix C.1), and decryption inverts encryption
    key = bytes(range(16))
    plain = bytes.fromhex("00112233445566778899aabbccddeeff")
    aes = K.AES(key)
    cipher = aes.enc(plain)
    lab.row("AES-128 on the FIPS-197 example", f"{cipher.hex()}   (the standard: 69c4e0d8...b4c55a)")
    assert cipher.hex() == "69c4e0d86a7b0430d8cdb78070b4c55a" and aes.dec(cipher) == plain

    # 2. the avalanche: one flipped plaintext bit, counted after every round
    diff = np.array(K.avalanche_by_round(rng, trials=TRIALS))
    mean, sd = diff.mean(axis=0), diff.std(axis=0)
    lab.row("bits differing after rounds 0, 1, 2", f"{mean[0]:.1f}, {mean[1]:.1f}, {mean[2]:.1f}   (the film: 1, 16.1, 64.4)")
    lab.row("after ten rounds", f"mean {mean[10]:.1f}, s.d. {sd[10]:.2f}   (Binomial(128, 1/2): 64, {np.sqrt(32):.2f})")
    assert mean[0] == 1 and 12 < mean[1] < 20, "one round reaches one column: about half of 32 bits"
    assert all(abs(m - 64) < 4 * np.sqrt(32 / TRIALS) + 0.2 for m in mean[2:]), "from round 2 on: half the bits"
    assert 4.3 < sd[10] < 7.2

    # 3. ECB leaks equal blocks; CBC does not
    image = bytes(40 + 50 * ((x // 8 + y // 4) % 4) for y in range(48) for x in range(64))      # diagonal stripes
    blocks = lambda data: {data[i:i + 16] for i in range(0, len(data), 16)}
    iv = bytes(rng.randrange(256) for _ in range(16))
    ecb, cbc = K.ecb_encrypt(aes, image), K.cbc_encrypt(aes, iv, image)
    lab.row(f"image of {len(image) // 16} blocks, {len(blocks(image))} distinct",
            f"ECB: {len(blocks(ecb))} distinct ciphertext blocks   CBC: {len(blocks(cbc))}")
    assert len(blocks(ecb)) == len(blocks(image)) < 10 and len(blocks(cbc)) == len(image) // 16
    assert K.cbc_decrypt(aes, iv, cbc) == image

    # 4. birthday collisions on SHA-256 cut to n bits
    need, theory = [], []
    for bits in BITS:
        trials = 200 if bits <= 16 else 40
        need.append(np.mean([K.birthday_trial(bits, rng) for _ in range(trials)]))
        theory.append(np.sqrt(np.pi / 2) * 2 ** (bits / 2))
        lab.row(f"collision on {bits} bits", f"{need[-1]:.0f} hashes on average   sqrt(pi/2) 2^(n/2) = {theory[-1]:.0f}")
        assert abs(need[-1] / theory[-1] - 1) < (0.2 if bits <= 16 else 0.4), "collisions come at the square root"
    lab.note = ("Two rounds of AES spread one bit over the whole state, and an n-bit hash resists collisions for only "
                "about 2^(n/2) tries; the cipher is sound, and the ECB leak comes from how it is used.")

    fig, ax = labs.figure(2, size=(11, 4.2))
    r = np.arange(11)
    ax[0].fill_between(r, mean - sd, mean + sd, color=labs.BLUE, alpha=0.25, label="± one s.d.")
    ax[0].plot(r, mean, "o-", color=labs.BLUE, label=f"mean over {TRIALS} random keys and blocks")
    ax[0].axhline(64, color=labs.GOLD, ls="--", label="64: half of the 128 bits")
    ax[0].set(title="AES-128: state bits that differ after one flipped input bit", xlabel="rounds completed",
              ylabel="bits differing", xticks=r)
    ax[0].legend(loc="lower right")
    grid = np.linspace(7, 21, 50)
    ax[1].semilogy(grid, np.sqrt(np.pi / 2) * 2 ** (grid / 2), color=labs.GOLD, label="√(π/2) · 2^(n/2)")
    ax[1].semilogy(grid, 2.0 ** grid, color=labs.MUTED, ls="--", label="2ⁿ: one try per possible value")
    ax[1].semilogy(BITS, need, "o", color=labs.RED, label="measured, truncated SHA-256")
    ax[1].set(title="Hashes until two collide", xlabel="hash length n (bits)", ylabel="hashes", xticks=BITS)
    ax[1].legend()
    lab.fig = fig
    return lab

Now change it

  1. Stop AES after 1, 2 and 3 rounds (rounds=) and count how many of the 16 bytes a one-bit change has reached. Why does full diffusion take two rounds?
  2. Encrypt the striped image in CTR mode with K.ctr_encrypt, then flip one ciphertext bit and decrypt. Which plaintext bits change, and what does that say about integrity?
  3. Run the birthday experiment at 24 bits. How many hashes do you predict, and how many would a 256-bit hash need?

Problems, with solutions

Try each problem before opening its solution.

  1. Shannon's theorem. Prove that perfect secrecy implies |K| ≥ |M|, and that the one-time pad with a uniform key is perfectly secret.

    Solution

    Let the message distribution give every message positive probability, and fix a ciphertext c with Pr[C = c] > 0. Decrypting c under every key gives the set D(c) = {Dec_k(c) : k ∈ K}, of size at most |K|. If |K| < |M|, some message m′ is not in D(c). Then no key turns m′ into c, so Pr[M = m′ | C = c] = 0, while Pr[M = m′] > 0. That contradicts perfect secrecy.

    For the pad on n bits, fix any m and c. Then Pr[C = c | M = m] = Pr[K = m ⊕ c] = 2⁻ⁿ, the same for every m. So Pr[C = c] = Σ_m Pr[C = c | M = m] Pr[M = m] = 2⁻ⁿ. Bayes' rule then gives Pr[M = m | C = c] = 2⁻ⁿ Pr[M = m] / 2⁻ⁿ = Pr[M = m].

  2. A stream cipher from a PRG. Show that if G is a PRG, then c = m ⊕ G(k) is secure for one message, by a reduction. Then break it for two messages under one key.

    Solution

    Suppose an adversary A, given m₀, m₁ of its choice and c = m_b ⊕ G(k), guesses b with probability ½ + ε. Build a distinguisher D for G. On input y, D runs A to get m₀, m₁, picks a random bit b, and gives A the value m_b ⊕ y. It outputs 1 if A guesses b.

    • If y = G(k), this is exactly A's game, so Pr[D = 1] = ½ + ε.
    • If y is uniform, m_b ⊕ y is uniform and independent of b, so Pr[D = 1] = ½.

    D's advantage is ε, so if G is a PRG, ε is negligible.

    With two messages under one key, c₁ ⊕ c₂ = m₁ ⊕ m₂. In the two-message game, the adversary submits (m, m) against (m, m′) with m ≠ m′. It outputs 0 exactly when c₁ = c₂. It is always right, so its advantage is ½. Chapter 4's crib dragging is the practical version.

  3. Feistel distinguishers. Give a distinguisher with advantage near 1 for the 2-round Feistel network, and one for 3 rounds when decryption queries are allowed.

    Solution

    Write a round as (L, R) ↦ (R, L ⊕ f(R)), with halves of h bits.

    Two rounds: (L, R) ↦ (L ⊕ f₁(R), R ⊕ f₂(L ⊕ f₁(R))). Query (L₁, R) and (L₂, R) with L₁ ≠ L₂, and output 1 if the left output halves XOR to L₁ ⊕ L₂. A 2-round network does this always. A random permutation does it with probability about 2⁻ʰ. The advantage is 1 − 2⁻ʰ, and chapter 7 measured 100% against 0%.

    Three rounds, with decryptions:

    1. Encrypt (L₁, R) to get (S₁, T₁).
    2. Encrypt (L₂, R) to get (S₂, T₂).
    3. Decrypt (S₂, T₂ ⊕ L₁ ⊕ L₂) to get (L₃, R₃).
    4. Output 1 if R₃ = S₁ ⊕ S₂ ⊕ R.

    Following the rounds:

    • The decryption's middle value becomes X₁ = L₁ ⊕ f₁(R).
    • Since S_i = R ⊕ f₂(X_i), we have R₃ = S₂ ⊕ f₂(X₁) = S₂ ⊕ S₁ ⊕ R, always.

    A random permutation satisfies it with probability about 2⁻ʰ. That is why Luby and Rackoff need four rounds for a strong PRP.

  4. CBC-MAC and lengths. Show that CBC-MAC is insecure for messages of different lengths, and that prefixing the length defeats the splice.

    Solution

    Let one-block messages m₁ and m₂ have tags t₁ = E_k(m₁) and t₂ = E_k(m₂). For the two-block message m₁ ‖ (m₂ ⊕ t₁), the chain computes E_k(E_k(m₁) ⊕ m₂ ⊕ t₁) = E_k(m₂) = t₂. That is a valid tag for a message never queried.

    Now prefix a block holding the length. The tag of a one-block message is then E_k(E_k(1) ⊕ m₁). The forger needs the chain's state after "2 blocks, m₁", which is E_k(E_k(2) ⊕ m₁). That value is unrelated to any tag it has seen.

    More generally, with a length prefix no message's encoding is a proper prefix of another's. On such prefix-free sets, CBC-MAC is a secure PRF when E is a PRP (Bellare, Kilian and Rogaway; Petrank and Rackoff). CMAC achieves the same result by masking the last block with a derived subkey.

  5. Build: attack your own server, then fix it. Write a padding-oracle server with this part's AES-CBC, recover a message and count queries. Then fix it with encrypt-then-MAC.

    Solution

    The server is a function oracle(iv, c) that runs pkcs7_unpad(cbc_decrypt(aes, iv, c)) and returns whether it raised. crypto.padding_oracle_attack(iv, c, oracle) recovers each block from right to left, with at most 256 queries a byte and about 128 on average. Chapter 10 measured 134.

    The fix:

    • Compute t = hmac_sha256(k_mac, iv + c) at encryption.
    • At decryption, check t with hmac.compare_digest before decrypting.
    • Return one error for every failure.

    The oracle now answers "invalid" for every doctored ciphertext, because the attacker cannot produce a valid tag, and the attack learns nothing. Use separate keys for encryption and the MAC. Better still, use an AEAD mode.

  6. ★ Research: how much do trails cluster? For Heys' SPN with 3 to 6 rounds, compute the exact expected probability of the best differential over all trails. Compare it with the best single trail.

    Where to start. With independent uniform round keys the cipher is a Markov cipher (Lai, Massey and Murphy, 1991). The expected probability that input difference α becomes β after r rounds is then an entry of Mʳ, where M is the 2¹⁶ × 2¹⁶ difference-transition matrix of one round: the S-box layer, then the permutation.

    M is sparse. Each row's support is the product of the S-boxes' nonzero table entries for the active nibbles. So for a fixed α, propagate a vector of 2¹⁶ probabilities r times. Maximise over α by symmetry and pruning, since only low-weight α are plausible.

    Compare max_β EDP(α, β) with the best single trail, found by a branch-and-bound search over trails (Matsui's algorithm). Then ask how fast the ratio grows with r. Background:

    • Keliher and Sui (2007) computed such exact values for two rounds of AES.
    • Daemen and Rijmen (2007) discussed "plateau trails".
    • Ankele and Kölbl (2018), "Mind the gap", measured clustering in modern lightweight ciphers.

    Nobody can compute these sums for full-size ciphers, which is why designers bound single trails instead.

Notes and sources

Glossary

密码学 cryptography · 密钥 key · 明文 plaintext · 密文 ciphertext · 替换密码 substitution cipher · 频率分析 frequency analysis · 爬山法 hill climbing · 维吉尼亚密码 Vigenère cipher · 重合指数 index of coincidence · 转子 rotor · 反射器 reflector · 接线板 plugboard · 共轭 conjugation · 循环结构 cycle structure · 已知明文片段 crib · 一次一密 one-time pad · 完美保密 perfect secrecy · Kerckhoffs 原则 · 可忽略 negligible · 选择明文攻击下的不可区分性 IND-CPA · 语义安全 semantic security · 归约 reduction · 伪随机生成器 pseudorandom generator (PRG) · 单向函数 one-way function · 流密码 stream cipher · 随机数 nonce · 伪随机函数 pseudorandom function (PRF) · 混合论证 hybrid argument · 伪随机置换 pseudorandom permutation (PRP) · Feistel 网络 · 分组密码 block cipher · 代换–置换网络 SPN · S 盒 S-box · 雪崩效应 avalanche effect · 工作模式 mode of operation · 填充预言机 padding oracle · 可延展性 malleability · 消息认证码 MAC · 认证加密 authenticated encryption (AEAD) · 哈希函数 hash function · 抗碰撞性 collision resistance · 生日界 birthday bound · 长度扩展 length extension · 海绵结构 sponge · Merkle 树 Merkle tree · 承诺 commitment · 盐 salt · 内存困难 memory-hard · 差分密码分析 differential cryptanalysis · 线性密码分析 linear cryptanalysis · 中间相遇 meet in the middle · 侧信道 side channel · 常数时间 constant time · 迷你密码国 Minicrypt · 密钥交替密码 key-alternating cipher · 轻量级密码 lightweight cryptography

Sources

Canon. Books:

  • Katz & Lindell, Introduction to Modern Cryptography (3rd ed., 2020);
  • Boneh & Shoup, A Graduate Course in Applied Cryptography (v0.6, 2023);
  • Goldreich, Foundations of Cryptography I–II (2001, 2004);
  • Menezes, van Oorschot & Vanstone, Handbook of Applied Cryptography (1996);
  • Daemen & Rijmen, The Design of Rijndael (2nd ed., 2020);
  • Ferguson, Schneier & Kohno, Cryptography Engineering (2010);
  • Kahn, The Codebreakers (1967, rev. 1996); Singh, The Code Book (1999).

Papers and standards:

  • Classical: al-Kindi, Risāla fī istikhrāj al-muʿammā (9th c.); Kasiski (1863); Friedman, The Index of Coincidence (1922); Rejewski, "How Polish mathematicians deciphered the Enigma" (1981).
  • Foundations: Shannon (1949); Kerckhoffs (1883); Goldwasser & Micali (1984); Yao (1982); Blum & Micali (1984); Goldreich & Levin (1989); Håstad, Impagliazzo, Levin & Luby (1999); Goldreich, Goldwasser & Micali (1986); Luby & Rackoff (1988); Impagliazzo (1995); Liu & Pass (2020).
  • Ciphers and modes: FIPS 46 (DES); FIPS 197 (AES); Bernstein, "ChaCha" (2008), RFC 8439; Ehrsam, Meyer, Smith & Tuchman (CBC, 1976); Vaudenay (2002); Bhargavan & Leurent, "Sweet32" (2016); Bogdanov, Khovratovich & Rechberger (2011).
  • Integrity and hashes: Bellare, Kilian & Rogaway (1994); Bellare, Canetti & Krawczyk (1996); Bellare & Namprempre (2000); McGrew & Viega, GCM (2004), SP 800-38D; Joux (2006); Böck et al., "Nonce-disrespecting adversaries" (2016); Merkle (1979, 1989); Damgård (1989); Wang & Yu (2005); Stevens et al., "SHAttered" (2017); Leurent & Peyrin (2020); Bertoni, Daemen, Peeters & Van Assche, Keccak (2011), FIPS 202; Percival, scrypt (2009); Biryukov, Dinu & Khovratovich, Argon2 (2016).
  • Attacks: Biham & Shamir (1991); Matsui (1993); Coppersmith (1994); Heys, "A tutorial on linear and differential cryptanalysis" (2002); Diffie & Hellman (1977); Kocher (1996); Kocher, Jaffe & Jun (1999); Bernstein (2005); Osvik, Shamir & Tromer (2006); Debian Security Advisory DSA-1571 (2008); Shumow & Ferguson (2007).
  • Frontier: Grover (1996); Simon (1994); Kuwakado & Morii (2010, 2012); Kaplan, Leurent, Leverrier & Naya-Plasencia (2016); Even & Mansour (1991); Chen & Steinberger (2014); Dobraunig, Eichlseder, Mendel & Schläffer, Ascon (2021); Jain, Lin & Sahai (2021); Lai, Massey & Murphy (1991); Keliher & Sui (2007); Ankele & Kölbl (2018).
About this partfrom its README

Part 29 of a sixty-one-part course in computer science (see the series plan and the syllabus), the fifth part of Act V, Limits and Secrets. For two thousand years ciphers were broken by counting letters. Shannon proved in 1949 that perfect secrecy needs a key as long as the message. Modern cryptography gets around his theorem by limiting the attacker's computing power, and builds pseudorandomness, block ciphers and hash functions on that assumption. The attacks in this part show how much care it takes. Every cipher and attack here is built from scratch and run; the code is for learning, never for real use, as the video says on screen.

The instrument is crypto.py. It holds:

  • classical ciphers and their breaks:
    • Caesar, substitution and Vigenère;
    • a quadgram language model with hill climbing from al-Kindi's frequency-matched start;
    • the index of coincidence, and χ² shift recovery;
  • an Enigma I simulator (rotors I–V, reflector B, plugboard, double stepping), cycle decomposition and Rejewski's characteristic;
  • the one-time pad and crib dragging; LFSRs, and Berlekamp–Massey over GF(2);
  • ChaCha20 (RFC 8439);
  • AES-128 from scratch:
    • the S-box built from inversion in GF(2⁸) mod x⁸ + x⁴ + x³ + x + 1 and the affine map;
    • the key schedule, encryption with a per-step trace, and decryption;
  • ECB, CBC and CTR modes; PKCS#7 padding and Vaudenay's padding-oracle attack;
  • SHA-256 (Merkle–Damgård) and the length-extension attack; HMAC; CBC-MAC; GHASH and AES-GCM; Keccak-f[1600] and SHA3-256;
  • birthday collision search; Merkle trees and inclusion proofs;
  • Heys' 16-bit SPN, its difference table and a differential attack on the last round; a 16-bit toy cipher and the meet-in-the-middle attack on its double encryption;
  • early-exit and fixed-work comparison loops; a PID-seeded key generator.

The block-cipher interface implements AES-128 on complete 16-byte blocks; callers pad explicitly. The ChaCha20 interface follows the IETF 32-bit counter/96-bit nonce layout and rejects counter exhaustion. The GCM example accepts 96-bit nonces and emits full 128-bit tags. Nonce requirements depend on the mode: CBC needs unpredictable IVs, while CTR and GCM require nonce/counter uniqueness under a key.

Encrypt-then-MAC relies on IND-CPA encryption, a strongly unforgeable MAC, independent keys, and authentication of the complete ciphertext including its IV. Verify before decrypting. The timing plots are local Python measurements; the fixed-work loop illustrates removing early exit and does not establish constant-time execution. Use hmac.compare_digest for tag comparisons. A bytewise timing attack requires a reliable statistical signal and may need many measurements for each candidate.

It is tested in tests/test_cs29_crypto.py, against published vectors where they exist:

  • AES-128 against FIPS-197 Appendices B and C.1, and S(0x53) = 0xED;
  • ChaCha20 against the RFC 8439 quarter-round and block vectors;
  • AES-GCM against the NIST test cases 1 and 2;
  • SHA-256, SHA3-256 and HMAC-SHA256 against hashlib and hmac;
  • the Enigma test vector (AAAAA → BDZGO with rotors I, II, III at AAA); its involution property; and the invariance of the characteristic under the plugboard.

The attacks are also tested: length extension, the padding oracle, Berlekamp–Massey, the SPN differential attack, Vigenère round trips, Merkle proofs and both comparisons.

  • Two thousand years of secrets. Hook.
    • Our 128 × 96 logo under AES: in ECB, 85 distinct blocks out of 768 and the logo is visible; in CBC, 768 distinct blocks.
    • A timeline from Caesar to AES; Shannon's theorem; the bounded attacker.
  • 1. Substitution and frequency analysis.
    • 26! ≈ 4 × 10²⁶ keys, 13 billion years at a billion keys a second.
    • Letter counts of 600 letters of Moby-Dick under a random key against English: W (12.8%) is E (12.7%).
    • Hill climbing on quadgram scores, from six million letters of other novels: one restart stuck at −3647, five reach −2488. The whole text is recovered, 100% correct, in 5.5 s.
  • 2. Vigenère and the index of coincidence.
    • The keyword BABBAGE; five plaintext E's enciphered as K, E, F, E, K.
    • The index of coincidence: plaintext 0.062, ciphertext 0.045, random 0.038; by key length, peaks at 7 (0.065) and 14.
    • Column-by-column χ² recovers BABBAGE; all 600 letters decrypt.
  • 3. Enigma.
    • Rotors as permutations; the reflector; no letter enciphers to itself; 150,738,274,937,250 plugboard settings and 1.59 × 10²⁰ daily keys.
    • Rejewski's theorem: two 13-cycles with and without ten plugboard cables. The characteristic (13,13; 12,12,1,1; 13,13) is unchanged, because conjugation preserves cycle type; another setting gives (8,8,3,3,2,2; …).
    • Cribs: WETTERBERICHT rules out 9 of 15 positions; the Bombe; Colossus.
  • 4. Perfect secrecy.
    • Vernam's pad; Shannon's definition and the proof for the pad; the 2-bit Latin square.
    • |K| ≥ |M|, proved.
    • A two-time pad broken by dragging " THE ": hits at offsets 4, 17 and 22. VENONA.
  • 5. What secure means.
    • Kerckhoffs; polynomial-time attackers; negligible advantage.
    • Work on a log scale: 2⁵⁶ (Deep Crack), 2⁶⁴, 2⁹⁴ (a year of Bitcoin mining), 2¹²⁸.
    • IND-CPA as a game; why encryption must be randomised; proof by reduction.
  • 6. Pseudorandom generators.
    • The definition and the stream cipher's reduction; Yao's next-bit test; PRGs from any one-way function.
    • A 17-bit LFSR (period 131,071) predicted completely from 34 bits by Berlekamp–Massey.
    • ChaCha20: the state, the quarter-round, column and diagonal rounds; RFC 8439 vectors; 677 KB/s in Python.
  • 7. Pseudorandom functions and permutations.
    • The GGM tree with SHA-256 as the generator: F(101) = 415c14be….
    • Feistel networks: the 2-round distinguisher fires in 100% of 2,000 trials for 1 and 2 rounds, 0% for 3. Luby–Rackoff.
    • The PRP/PRF switching lemma and Sweet32.
  • 8. AES.
    • DES against AES, and the contest.
    • One round on FIPS-197's example: SubBytes (S(0x53): inverse 0xCA, output 0xED), ShiftRows, MixColumns, AddRoundKey.
    • Ten rounds give 69c4e0d86a7b0430d8cdb78070b4c55a, as in the standard.
  • 9. The avalanche.
    • One flipped bit after rounds 0–4: 1, 17, 62, 64 and 71 bits differ (1, 4 and then all 16 bytes).
    • 400 trials: means of 1, 16.1 and 64.4 bits after rounds 0–2. After ten rounds, mean 63.6 and s.d. 5.45, against Binomial(128, ½).
    • Why ten rounds: seven-round attacks; the biclique attack at 2¹²⁶·¹.
  • 10. Modes of operation.
    • The logo under ECB, CBC and CTR.
    • The padding oracle explained, then run: "PIN=4921; transfer approved by the bank" recovered with 6,412 queries (134 a byte) in 2 s.
  • 11. Integrity.
    • CTR malleability: $0010 becomes $9910 without the key.
    • CBC-MAC's splice forgery, verified; HMAC.
    • Encrypt-then-MAC; GCM's GHASH as polynomial evaluation (NIST vectors match); nonce reuse; ChaCha20-Poly1305.
  • 12. Hash functions.
    • Birthday collisions on SHA-256 cut to 16–32 bits, against √(π/2) · 2ⁿᐟ².
    • MD5 and SHA-1 broken.
    • Merkle–Damgård and a length-extension forgery that verifies.
    • The SHA-3 sponge; ours matches hashlib.
  • 13. Hashes at work.
    • A Merkle tree over eight commits; a 3-hash inclusion proof; tampering detected.
    • Coin flipping by telephone with a commitment.
    • Password hashing measured: SHA-256 (0.45 µs), PBKDF2 × 100,000 and × 600,000, and scrypt (48 ms, 16 MB), with the time to try every 8-letter lowercase password.
  • 14. Cryptanalysis.
    • Heys' SPN and its difference table; a three-round trail of probability 27/1024.
    • The last-round attack on 5,000 pairs: the right key gets 146 counts and the best wrong guess 80. DES's S-boxes; linear cryptanalysis; AES's wide-trail bound.
    • Meet in the middle on double encryption: 131,072 cipher calls instead of 2³²; two candidates survive two pairs.
  • 15. Side channels and bad randomness.
    • Early-exit versus fixed-work comparison over 0–16 correct bytes; times depend on the runtime and host.
    • Cache attacks on AES T-tables; power analysis.
    • The Debian OpenSSL bug in miniature: a PID-seeded key found after 23,107 tries in 2 s. Dual_EC_DRBG.
  • 16. Frontier: proofs, quanta and lightweight ciphers.
    • Minicrypt; Liu–Pass.
    • Grover and Simon's attacks on modes.
    • Key-alternating ciphers (Even–Mansour; Chen–Steinberger); Ascon.
    • Open problems. Outro.

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Caesar, substitution and Vigenère; al-Kindi's frequency analysis, breaking a substitution cipher on a novel's paragraph; Kasiski and the index of coincidence.
  2. Enigma: rotors as permutations. Rejewski (1932) saw that the cycle structure survives the plugboard, because conjugation preserves cycle type. Turing's Bombe; Colossus and Lorenz.
  3. Perfect secrecy (Shannon 1949): the one-time pad; |K| ≥ |M| is necessary (proved); VENONA's reused pads.
  4. Modern definitions: Kerckhoffs; PPT adversaries; negligible functions; IND-CPA drawn as a game.
  5. PRGs: indistinguishability and next-bit unpredictability (Yao); Blum–Micali, hard-core bits (Goldreich–Levin); ChaCha20.
  6. PRFs: the GGM tree, by a hybrid argument; PRPs and Luby–Rackoff (three Feistel rounds give a PRP).
  7. Block ciphers:
    • DES (1977; broken by brute force by Deep Crack in 1998);
    • AES (2001): SubBytes (inversion in GF(2⁸), callback to Part 28), ShiftRows, MixColumns (an MDS matrix), AddRoundKey;
    • the avalanche effect, where one flipped bit changes half the output.
  8. Modes: the ECB penguin (computed on our own image); CBC and Vaudenay's padding oracle (2002); CTR.
  9. Integrity: CBC-MAC and HMAC; authenticated encryption; GCM's GHASH as polynomial evaluation; ChaCha20-Poly1305.
  10. Hashes:
    • the birthday bound 2^{n/2} (callback to Part 17);
    • Merkle–Damgård and length extension;
    • MD5 and SHA-1 collisions (Wang 2004; SHAttered 2017);
    • the SHA-3 sponge.
  11. Hash applications: Merkle trees (git, certificate transparency, Part 38's blockchains); commitments; salted, slow, memory-hard password hashing (bcrypt, scrypt, Argon2).
  12. Cryptanalysis on a toy SPN: differential (Biham & Shamir; DES's S-boxes, hardened against it in 1974) and linear (Matsui); meet-in-the-middle and why 2DES fails.
  13. Side channels: timing (Kocher 1996) and constant-time code; power analysis; cache attacks on AES T-tables (callback to Parts 8–9).
  14. Randomness failures: the Debian OpenSSL bug (2008); Dual_EC_DRBG. Outro.

Computed: frequency analysis breaking a cipher; an Enigma simulation and its cycle structures; the ECB penguin (our own logo); AES from scratch against FIPS-197 vectors; avalanche statistics; a toy differential attack on a 4-round SPN; birthday collisions on truncated SHA-256. Visuals: the penguin under ECB against noise under CBC; AES's 4 × 4 state transforming round by round; an avalanche heatmap; rotors stepping; the sponge absorbing and squeezing. In practice: TLS cipher suites, disk and database encryption, password storage, HMAC-signed tokens, constant-time code review. Reading: Katz & Lindell, Introduction to Modern Cryptography; Boneh & Shoup, A Graduate Course in Applied Cryptography; Goldreich, Foundations of Cryptography I–II; Menezes, van Oorschot & Vanstone, Handbook of Applied Cryptography; Daemen & Rijmen, The Design of Rijndael; Ferguson, Schneier & Kohno, Cryptography Engineering; Kahn, The Codebreakers; Singh, The Code Book; Shannon 1949; Heys' tutorial on linear and differential cryptanalysis.

中文讲义

本讲的中文部分(与英文版对应)。

习题与解答
  1. Shannon 定理。 证明完美保密蕴含 |K| ≥ |M|,并证明密钥均匀的一次一密是完美保密的。

    解答

    设消息分布给每个消息正概率,固定一个 Pr[C = c] > 0 的密文 c。在每个密钥下解密 c,得到集合 D(c) = {Dec_k(c) : k ∈ K}, 其大小至多 |K|。若 |K| < |M|,就有某个消息 m′ 不在 D(c) 中:没有密钥把 m′ 变成 c,所以 Pr[M = m′ | C = c] = 0,而 Pr[M = m′] > 0, 与完美保密矛盾。对 n 位的一次一密,任取 m 与 c,Pr[C = c | M = m] = Pr[K = m ⊕ c] = 2⁻ⁿ,对每个 m 都一样;所以 Pr[C = c] = Σ_m Pr[C = c | M = m] Pr[M = m] = 2⁻ⁿ,再由 Bayes 公式,Pr[M = m | C = c] = 2⁻ⁿ Pr[M = m] / 2⁻ⁿ = Pr[M = m]。

  2. 由 PRG 构造流密码。 证明若 G 是 PRG,则 c = m ⊕ G(k) 对一条消息是安全的(用归约);再对同一密钥下的两条消息攻破它。

    解答

    设敌手 A 拿到自己选的 m₀、m₁ 与 c = m_b ⊕ G(k),以 ½ + ε 的概率猜中 b。构造 G 的区分器 D:输入 y 时,D 运行 A 得到 m₀、m₁, 随机取一位 b,把 m_b ⊕ y 交给 A,A 猜中 b 就输出 1。若 y = G(k),这正是 A 的游戏,Pr[D = 1] = ½ + ε;若 y 均匀,m_b ⊕ y 均匀且与 b 独立,Pr[D = 1] = ½。所以 D 的优势是 ε;G 是 PRG,ε 就可忽略。同一密钥下两条消息:c₁ ⊕ c₂ = m₁ ⊕ m₂。在两消息游戏中,敌手提交 (m, m) 对 (m, m′)(m ≠ m′),当且仅当 c₁ = c₂ 时输出 0:它总是对的,优势为 ½。第 4 章的拖曳猜词就是它的实战版。

  3. Feistel 区分器。 对 2 轮 Feistel 网络给出优势接近 1 的区分器;对 3 轮、允许解密查询的情形也给出一个。

    解答

    把一轮写成 (L, R) ↦ (R, L ⊕ f(R)),每半 h 位。两轮:(L, R) ↦ (L ⊕ f₁(R), R ⊕ f₂(L ⊕ f₁(R)))。查询 (L₁, R) 与 (L₂, R) (L₁ ≠ L₂),若两个输出的左半异或等于 L₁ ⊕ L₂ 就输出 1:2 轮网络总是如此,随机置换的概率约为 2⁻ʰ;优势 1 − 2⁻ʰ(第 7 章测得 100% 对 0%)。三轮且允许解密:加密 (L₁, R) 得 (S₁, T₁),加密 (L₂, R) 得 (S₂, T₂),解密 (S₂, T₂ ⊕ L₁ ⊕ L₂) 得 (L₃, R₃),若 R₃ = S₁ ⊕ S₂ ⊕ R 就输出 1。逐轮推演:解密时的中间值变为 X₁ = L₁ ⊕ f₁(R);又因 S_i = R ⊕ f₂(X_i),得 R₃ = S₂ ⊕ f₂(X₁) = S₂ ⊕ S₁ ⊕ R,恒成立。随机置换 满足它的概率约 2⁻ʰ。这就是 Luby 与 Rackoff 要四轮才能得到强 PRP 的原因。

  4. CBC-MAC 与长度。 证明 CBC-MAC 对不同长度的消息不安全,并证明前置长度能挫败拼接。

    解答

    设单块消息 m₁、m₂ 的标签为 t₁ = E_k(m₁)、t₂ = E_k(m₂)。对两块消息 m₁ ‖ (m₂ ⊕ t₁),链计算 E_k(E_k(m₁) ⊕ m₂ ⊕ t₁) = E_k(m₂) = t₂:一个从未查询过的消息的有效标签。现在前置一个存放长度的块:单块消息的标签是 E_k(E_k(1) ⊕ m₁),而伪造者需要的是 「2 块,m₁」之后链的状态 E_k(E_k(2) ⊕ m₁),它与见过的任何标签都无关。一般地,有了长度前缀,没有一个消息的编码是另一个的真前缀;在 这种无前缀集合上,只要 E 是 PRP,CBC-MAC 就是安全的 PRF(Bellare、Kilian 与 Rogaway;Petrank 与 Rackoff)。CMAC 用派生子密钥掩盖 最后一块,达到同样的效果。

  5. 动手:攻击自己的服务器,再修好它。 用本部分的 AES-CBC 写一个填充预言机服务器,恢复一条消息并数查询次数;然后用先加密后 MAC 修好它。

    解答

    服务器就是一个函数 oracle(iv, c):运行 pkcs7_unpad(cbc_decrypt(aes, iv, c)),返回是否抛出异常。 crypto.padding_oracle_attack(iv, c, oracle) 从右到左恢复每一块,每字节至多 256 次、平均约 128 次查询(第 10 章测得 134)。修复:加密时 计算 t = hmac_sha256(k_mac, iv + c);解密时先用 hmac.compare_digest 检查 t,再解密;任何失败都返回同一个错误。现在预言机对每个 篡改过的密文都答「无效」,因为攻击者造不出有效标签,攻击什么也学不到。加密与 MAC 用不同的密钥;更好的是直接用 AEAD 模式。

  6. ★ 研究:差分路径聚集有多严重? 对 3 到 6 轮的 Heys SPN,计算最佳差分在所有路径上求和的精确期望概率,并与最佳单条路径比较。

    从哪里入手。 轮密钥独立均匀时,这个密码是 Markov 密码(Lai、Massey 与 Murphy,1991),r 轮后输入差分 α 变成 β 的期望概率是 Mʳ 的 一个元素,其中 M 是一轮(S 盒层再接置换)的 2¹⁶ × 2¹⁶ 差分转移矩阵。M 是稀疏的:每行的支撑是活跃半字节上各 S 盒非零表项之积。所以对 固定的 α,把一个 2¹⁶ 维的概率向量传播 r 次;再利用对称性与剪枝对 α 取最大(只有低重量的 α 有希望)。把 max_β EDP(α, β) 与用分支定界 (Matsui 算法)找到的最佳单条路径比较,问这个比值随 r 增长多快。Keliher 与 Sui(2007)对两轮 AES 算出了这样的精确值;Daemen 与 Rijmen (2007)讨论了「平台路径」;Ankele 与 Kölbl(2018,《Mind the gap》)测量了现代轻量级密码中的聚集。对全尺寸密码,没有人能算出这些和, 所以设计者只能为单条路径定界。

Build the film

python -m videos.cs.cs29.compute        # the part's numbers, into .cache/cs29
python tools/build.py cs29                  # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs29 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/cs/cs29. Setup: see the course page. Source of these notes: the README and the scenes' narration.

Build it
python -m videos.cs.cs29.compute           # every number in the part (about two minutes)
python tools/build.py cs29 -q l            # a 480p preview
python tools/build.py cs29                 # 1080p