Turns the word secure into the chosen-plaintext (CPA) game, shows why every deterministic cipher and every predictable CBC IV loses it (the TLS 1.0 to BEAST story), then compares Encrypt-and-MAC, MAC-then-Encrypt and Encrypt-then-MAC with real AES and HMAC values and ends on AEAD in practice.
Subject: Computer Security · 68 slides · code lesson
Open the interactive version of this deck
Title
Computer Security — Crypto Lecture 7
From a loose word to a precise game, and from two good tools to one safe channel
Section
Pinning down a word we have been using loosely
Objectives
This lesson rebuilds part four of the cryptography lecture, the shortest part and the densest. It turns the word secure into a game you can play, uses the game to explain why ECB, deterministic schemes and predictable IVs all fail, and then asks how to combine encryption with a MAC without undoing either one.
Security I, Lecture 2: Cryptography, part four (when is a cipher secure?) slide s-div-def
Warm-up
Earlier lectures called ECB broken and one-time-pad reuse broken, and called AES secure. Before making the word precise, pull those examples back out.
Discussion prompt
Name one scheme from earlier that was called broken. What exactly could the attacker learn, and did they ever recover the key?
Hint: Think of the penguin picture.
Answer:
ECB was called broken because identical plaintext blocks give identical ciphertext blocks, so the outline of the penguin image shows through. Reusing a one-time pad was called broken because XORing two ciphertexts cancels the pad and leaves the XOR of the two messages.
In neither case did anyone recover the key. The attacker learned something about the messages: a pattern, a relationship, an equality. That is the clue for this lesson. A useful definition of secure has to rule out leaking anything about the message, not just leaking the key.
Concept
So far the course has used broken and secure informally. Informal words are fine until two people disagree, and then nobody can settle it. Is AES in ECB mode secure? AES is unbroken, yet the penguin shows through. Clearly secure must be a property of the whole scheme, the way it is used, and not just of the block cipher inside it.
Modern cryptography answers this with a precise definition written as a game between an attacker and a challenger. A scheme is secure if no efficient attacker can win the game noticeably more often than by guessing. The game is chosen so that winning it captures every leak we care about.
| informal claim | why it is not enough |
|---|---|
| the attacker cannot find the key | ECB leaks the image without anyone finding the key |
| the attacker cannot read the message | partial information, such as equality, still leaks |
| the cipher passes our tests | tests only show the attacks someone thought of |
Security I, Lecture 2: Cryptography, part four (when is a cipher secure?) slide s-div-def
Prediction
A weather station sends one bit a day, 0 for rain and 1 for shine, encrypted with AES under a key nobody else knows. The same bit always encrypts the same way.
Predict first
Is this encrypted forecast secure against someone who watches the wire for a week?
Correct: No: only two ciphertexts ever appear, so one known day reveals the rest
Why: Because the encryption is deterministic, rain always produces one ciphertext and shine always the other. An eavesdropper sees two values repeating. The moment she learns the weather on any single day, for example by looking out of the window, she can label both values and read every forecast from then on. AES was never attacked; the way it was used leaked everything.
Concept
Here are real AES-128 ciphertexts for the two possible messages. The station encrypts deterministically, so the same word always gives the same 16 bytes.
key = 000102030405060708090a0b0c0d0e0f # AES-128, ECB, PKCS#7
rain -> ab05b7b07ac522caa56fc90f9423982b
shine -> 612e203b3c9f98c908c4987f561dc8a2| day | on the wire | what Mallory concludes |
|---|---|---|
| Mon | ab05... | unknown, but it is one of two values |
| Tue | 612e... | she looks outside: sunny, so 612e... is shine |
| Wed | ab05... | the other value, so rain |
| Thu to Sun | ab05 or 612e | read instantly, forever |
Figure (svg): Seven days of ciphertext showing only two repeating values; once Tuesday is known to be sunny, every other day can be read
The bar this sets is high but unavoidable: a ciphertext must leak nothing at all, not even whether two messages are equal. And since a deterministic cipher always leaks equality, encryption must be randomized.
Security I, Lecture 2: Cryptography, part four (when is a cipher secure?) slide s-secure
Socratic
The weather example leaked no letters, no key and no bits of AES. It leaked one relation between messages.
Discussion prompt
Which relation did it leak, and why does hiding that relation force the encryption to use fresh randomness every time?
Hint: What did Mallory compare from day to day?
Answer:
It leaked equality: whether today's message is the same as an earlier one. Equality alone was enough to read the whole week once a single day was known.
To hide equality, encrypting the same message twice must give different ciphertexts. A fixed function of key and message cannot do that, because the same inputs always give the same output. So something must change on every call: a random IV, or a nonce that never repeats. Decryption still works because that value travels with the ciphertext.
Concept
The difference is easy to see on real bytes. ECB is deterministic. Counter mode (CTR) with a fresh nonce is randomized: the nonce changes, so the keystream changes, so the ciphertext changes.
key = 000102030405060708090a0b0c0d0e0f # AES-128
ECB("rain") = ab05b7b07ac522caa56fc90f9423982b
ECB("rain") again = ab05b7b07ac522caa56fc90f9423982b
CTR("rain", nonce 3f9a1c0e7b2d4a58) = de209349
CTR("rain", nonce c41e88b20f6d9e73) = d78e0aa2| scheme | same message twice gives | leaks equality? |
|---|---|---|
| AES-ECB | identical ciphertext | yes |
| AES-CTR, fresh nonce | unrelated ciphertexts | no |
| AES-CBC, fresh random IV | unrelated ciphertexts | no |
The nonce or IV is not secret; it is sent alongside the ciphertext. Its only job is to be different every time, and as Part 3 shows, for CBC also unpredictable.
Security I, Lecture 2: Cryptography, part four (when is a cipher secure?) slide s-secure
Discrimination
Sort each scheme by whether encrypting the same message twice under the same key gives the same ciphertext.
Sort into buckets
Deterministic or randomized?
Two truths and a lie
Three claims about what a definition of secure should say. Two are right.
Eliminate the wrong options
Which claim is the myth?
Survives elimination: t2
Why: Key recovery is the most extreme failure, but far from the only one. ECB, pad reuse and the weather station all leak information without the key ever being found. A good definition must rule out every leak about the message, which is why the next part defines security as a guessing game rather than as key secrecy.
Section
Which message was encrypted?
Concept
Before the game itself, a story that explains its strongest feature. Two crooks target a bank's cash machine. One stands at the machine and types in PINs of his choice; the other taps the wire and records the encrypted messages the machine sends to the bank. After enough tries they hold a codebook: this ciphertext means PIN 1234, that one means 0000. From then on they can read every customer's PIN off the wire.
The crooks never broke the cipher. They used the fact that they could influence what got encrypted. That is the chosen-plaintext setting, and it is not exotic: almost every real system encrypts data an outsider influences, such as a search query, a form field, a username, or a cookie set by a web page.
| attacker can | name of the model | realistic? |
|---|---|---|
| only see ciphertexts | ciphertext-only | the weakest attacker |
| also get chosen messages encrypted | chosen-plaintext (CPA) | yes: the minimum bar for real systems |
Notice that a deterministic cipher falls to the crooks at once, because the codebook is exact. A randomized one does not: the same PIN gives a different ciphertext every time, so the codebook is useless.
Security I, Lecture 2: Cryptography, part four (when is a cipher secure?) slide s-cpa
Concept
Start with the weakest attacker, who only sees a ciphertext. The game makes the question of what leaked as sharp as possible: the attacker picks the two messages, so if anything at all about them leaks, she can choose messages that differ in exactly that respect.
Figure (svg): Mallory sends two messages to the challenger, who holds the key, flips a coin b, and returns the encryption of message b; Mallory then guesses b
A blind guess wins half the time, so winning half the time proves nothing. Secure means nobody can do noticeably better than one half.
Security I, Lecture 2: Cryptography, part four (when is a cipher secure?) slide s-cpa
Ranking
Order the steps of one round of the ciphertext-only game.
Put in order
Why: The key exists before anything else and never leaves the challenger. Mallory commits to her two messages before the coin is flipped, so she cannot adapt them to the coin. She sees exactly one ciphertext and must name which message it hides.
Estimation
Mallory ignores the ciphertext completely and always answers 0.
Predict first
Over many rounds, how often does she win?
Correct: About half the time
Why: The coin is fair, so b is 0 in half the rounds and her fixed answer is right in exactly those. Any strategy that ignores the ciphertext, including a random guess, wins half the time. That is the baseline: security is measured as how far above one half an attacker can get by actually using what she sees.
Concept
Now give Mallory the crooks' power. Before and after the challenge she may ask the challenger to encrypt any message she likes, as often as she likes. This helper is called an encryption oracle. Everything else stays the same: two messages, one secret coin, one challenge ciphertext, one guess.
Figure (svg): The CPA game: Mallory may send any x to the encryption oracle and receive its encryption, then plays the same challenge as before
encryption oracle — a box that encrypts any message Mallory submits under the secret key, without ever revealing the key
CPA-secure — even with the oracle, no efficient Mallory wins the challenge noticeably more often than one half
Why is this the right definition? If any single bit of information about the plaintext leaked, Mallory could pick m0 and m1 that differ in that bit and win. So staying stuck at one half means nothing leaks. This is the standard definition called IND-CPA, indistinguishability under chosen-plaintext attack.
Security I, Lecture 2: Cryptography, part four (when is a cipher secure?) slide s-cpa-game
Matching
Match each piece of the CPA game to its role.
Match the pairs
Why: The game reduces every possible leak to one bit, b. The challenger is the honest system, the oracle models data an outsider can influence, and one half is the score of an attacker who learned nothing from the ciphertext.
Socratic
Every version of the game insists that the two challenge messages have equal length.
Discussion prompt
What would go wrong with the definition if Mallory could pick m0 = a single byte and m1 = a whole megabyte?
Hint: What does every ciphertext reveal at a glance?
Answer:
She would win every time just by looking at the size of the ciphertext. Practical encryption reveals roughly how long the message is; hiding length completely would mean padding every message to some maximum size.
The definition makes a deliberate choice: length is allowed to leak, everything else is not. That is also a reminder for real systems. If message length matters, for example a yes versus a no, or which page of a site was loaded, encryption alone will not hide it.
Explain it to yourself
The game asks only one question, which of two messages, yet it is claimed to rule out every kind of leak.
Discussion prompt
Suppose a scheme leaked just the first bit of every message. Explain how Mallory would use the game to show it, and why that makes the game a complete test.
Hint: She chooses the two messages. What should they differ in?
Answer:
She picks m0 starting with a 0 bit and m1 starting with a 1 bit, otherwise identical. Whatever leaks the first bit of the challenge plaintext tells her b directly, so she wins every round.
The same trick works for any property that leaks: equality with an earlier message, a checksum, the parity, the first character. She chooses two messages that differ in exactly that property. So if nobody can beat one half, no property of the plaintext can be leaking.
Concept
Now the payoff. Take any deterministic scheme, however strong its block cipher. Mallory needs exactly one oracle call to win every round.
Figure (svg): Mallory asks the oracle to encrypt m0 and keeps c0; in the challenge she compares c with c0 and answers 0 if they match, 1 otherwise
Deterministic means the encryption of m0 is always the same bytes, so the challenge equals c0 exactly when b is 0. She is right every round. ECB is precisely this scheme, which is the formal reason the penguin shows through. The fix is the one the weather station needed: a fresh IV or nonce every time.
Security I, Lecture 2: Cryptography, part four (when is a cipher secure?) slide s-deterministic
Faded example
Here is Mallory's whole strategy against a deterministic scheme, written as code. Fill in what she answers in each branch.
Fill in the blanks
c0 = oracle(m0) # one call before the challenge
c = challenge(m0, m1) # the encryption of m_b
if c == c0:
guess = 0
else:
guess = 1
Why: If the challenge equals the oracle's encryption of m0, the challenger must have encrypted m0, so b is 0. If it differs it cannot be m0, because a deterministic scheme gives m0 the same ciphertext every time, so it was m1 and b is 1. The guess is right every round.
Counterexample
A classmate argues: AES is an unbroken block cipher, ECB just applies AES to each block, so ECB inherits AES's security.
Discussion prompt
Give a concrete counterexample to the classmate's conclusion, and name the step of the argument that fails.
Hint: Try the one-oracle-call strategy.
Answer:
Counterexample: the deterministic strategy from the last slide. Ask the oracle for the encryption of m0, challenge on m0 and m1, compare. It wins every round against ECB, so ECB is not CPA-secure, while AES itself remains unbroken.
The failing step is inherits. AES is secure as a single fixed permutation used once per distinct input. ECB uses it as a deterministic encryption scheme, and the CPA game punishes determinism no matter how good the permutation is. Security belongs to the scheme as used, not to its parts.
Concept
Winning every round is an obvious break. But what about an attacker who wins 51 percent of the time? We need a number. The advantage measures how far an attacker's success sits from the coin-flip baseline.
Figure (svg): A number line from 0 to 1 with one half marked as secure and 1 as broken; an attacker who wins 75 percent sits a quarter of the way above one half
Advantage = | Pr[ b' = b ] - 1/2 |
# an equivalent form, often used in proofs, is twice as large:
Adv = | Pr[ b' = 1 when b = 1 ] - Pr[ b' = 1 when b = 0 ] || attacker | wins | first form | second form |
|---|---|---|---|
| blind guess | 50% | 0 | 0 |
| wins 75% of rounds | 75% | 0.25 | 0.5 |
| always right | 100% | 0.5 | 1 |
The second form is exactly twice the first, so always right scores 1 there, which is why people say a deterministic scheme loses with advantage 1. A scheme is CPA-secure when the advantage is negligible for every efficient attacker. In practice negligible means no better than about one half plus 2 to the power -128.
Security I, Lecture 2: Cryptography, part four (when is a cipher secure?) slide s-cpa-def
Fill the middle
An attacker answers 1 in 80% of rounds where b = 1, and in 30% of rounds where b = 0. The coin is fair. Work out both forms of the advantage.
Fill in the blanks
Pr[b' = b] = (0.80 + (1 - 0.30)) / 2 = 0.75
first form = | 0.75 - 0.5 | = 0.25
second form = | 0.80 - 0.30 | = 0.5
Why: When b = 1 she is right if she answers 1, which happens 80% of the time; when b = 0 she is right if she answers 0, which happens 70% of the time. Each case is half the rounds, so she wins (0.80 + 0.70) / 2 = 0.75. The first form is 0.75 - 0.5 = 0.25 and the second is 0.80 - 0.30 = 0.5, twice as large, as always. Either way this scheme is badly broken.
Estimation
Negligible advantage in practice means something like 2 to the power -128.
Predict first
Roughly what is 2 to the power -128 as a decimal?
Correct: About 3 times 10 to the power -39
Why: 2 to the power 128 is about 3.4 times 10 to the power 38, so its reciprocal is about 2.9 times 10 to the power -39. An attacker with that advantage would have to run the game around 10 to the power 77 times before her edge over guessing became visible, far beyond any computer that could ever be built. That is why such an advantage counts as zero for every practical purpose.
Edge cases
Advantage is a continuum, but the definition draws a line between negligible and not.
Discussion prompt
Attacker A wins 50.0001% of rounds against a scheme. Attacker B wins 50% plus 2 to the power -128. Is either scheme broken? What would you need to know besides the percentage?
Hint: Think about repeating the game many times, and about how long each attack takes.
Answer:
Attacker B's edge is negligible: the scheme counts as secure. Attacker A's edge of one in a million is not negligible. Repeating the game a few trillion times would make it statistically obvious, and in a real protocol it could leak information over many messages. Cryptographers would call that scheme broken, even though one round reveals almost nothing.
You would also need the attacker's cost. The definition only counts efficient attackers. An attacker who wins with advantage 1 but must try every one of 2 to the power 128 keys is not efficient, which is why brute force does not count as breaking AES.
Pattern
Whenever someone proposes an encryption scheme, the CPA game turns the question is it secure into a short routine.
| scheme | property that shows | advantage |
|---|---|---|
| AES-ECB | equality of messages | 1, the maximum |
| the weather station | equality of forecasts | 1 |
| AES-CTR with fresh nonces | only length | negligible |
Check
Solve it on paper before you click.
Check your understanding
Which result shows that a scheme is NOT CPA-secure?
Answer: B
Why: An efficient attacker with a 14-point edge over guessing has non-negligible advantage, so the scheme fails the definition. Exactly 50% is no advantage at all. Brute force over all keys is not efficient, so it does not count. Passing a statistics test is evidence but not proof; the definition is about every efficient attacker, not one test.
Concept
Lock the game in before using it. This is the version to keep in your head for the rest of the course; the next lecture asks the same kind of question about integrity.
Figure (svg): The CPA game: oracle queries, then a challenge on m0 and m1 with a hidden coin, then a guess
| rule | what it means |
|---|---|
| oracle, any x, any number of times | outsiders can influence what gets encrypted |
| challenge on m0 and m1 of equal length | only length may leak |
| advantage negligible for every efficient attacker | nothing else about the plaintext leaks |
| consequence | deterministic schemes, and schemes whose randomness can be predicted, lose |
Security I, Lecture 2: Cryptography, part four (when is a cipher secure?) slide s-recap-cpa
Section
Randomized on paper, deterministic to the attacker
Concept
The lecture's last symmetric-encryption lab is not a toy. Its bug shipped in TLS 1.0, the protocol behind HTTPS, and sat in every browser for twelve years.
Figure (svg): Timeline: 1999 TLS 1.0 ships CBC with a chained IV; 2002 Rogaway and Moller warn about it; 2006 TLS 1.1 uses a fresh IV per record; 2011 the BEAST attack decrypts cookies live
| year | event |
|---|---|
| 1999 | TLS 1.0 ships CBC; each record's IV is the last ciphertext block of the previous record |
| 2002 | Rogaway, then Moller, point out that a predictable IV breaks chosen-plaintext security |
| 2006 | TLS 1.1 fixes it with an explicit, fresh IV in every record |
| 2011 | Duong and Rizzo's BEAST attack decrypts HTTPS session cookies in a live demo, and the world finally upgrades |
The lesson of the history is as important as the cryptography. The fix was published five years before the attack and adopted only after it. A theoretical break in the CPA game is a real break waiting for an engineer.
Security I, Lecture 2: Cryptography, part four (when is a cipher secure?) slide s-cpa-intro
Concept
The lab server copies TLS 1.0 in miniature. It encrypts with real AES-128 in CBC mode. The first message gets a random IV. Every later message reuses the last ciphertext block of the previous reply as its IV.
Figure (svg): Message 1 uses a random IV1 and produces C1 and C2; message 2 uses IV2 equal to C2, which was already sent
# message 1
iv1 = random 16 bytes
reply = iv1 || CBC_K(iv1, pad(msg1)) # ends with block C2
# message 2: no new randomness
iv2 = last block of the previous reply # the receiver already has it
reply = iv2 || CBC_K(iv2, pad(msg2))| message | IV | who knows it before encryption |
|---|---|---|
| 1 | fresh random bytes | nobody |
| 2 | the last block of reply 1 | anyone who saw reply 1 |
| 3 | the last block of reply 2 | anyone who saw reply 2 |
The output always looks fresh, and the same message never encrypts the same way twice. So it is not the deterministic scheme that lost in Part 2. The flaw is subtler: the next IV is public before the message that uses it is chosen.
Security I, Lecture 2: Cryptography, part four (when is a cipher secure?) slide s-cpa-scheme
Prediction
Every ciphertext from the chained-IV scheme looks random, and encrypting the same message twice gives different bytes.
Predict first
Is the chained-IV scheme CPA-secure?
Correct: No: the attacker knows each IV before she chooses the next message
Why: Randomness only protects you if the attacker cannot predict it when she picks her input. Here she can, because the next IV is the last block she has just received. CBC itself is fine: with a fresh, unpredictable IV per message it is CPA-secure. The chaining rule is what loses the game.
Trap
A common belief: if every ciphertext looks like random bytes and the same message never encrypts the same way twice, the scheme must be CPA-secure.
| claim | reality |
|---|---|
| the output passes randomness tests | true for the chained-IV scheme, and irrelevant |
| the same message gives different ciphertexts | true, because the IVs differ |
| so the attacker cannot exploit the randomness | false: she knew each IV before choosing her message |
What matters is not how random the output looks afterwards but whether the attacker could predict the randomness at the moment she chose her input. CPA security is a statement about every efficient attacker in the game, not about how ciphertexts look to a statistics test.
The check to run on any design: list every value that varies between encryptions and ask who knows it, and when. If the attacker knows it before choosing a message, treat it as fixed.
Security I, Lecture 2: Cryptography, part four (when is a cipher secure?) slide s-cpa-scheme
Socratic
In CBC, the first block AES sees is the first plaintext block XORed with the IV. The IV is the only randomness in the whole encryption.
Discussion prompt
If Mallory knows the IV before she chooses her message, who effectively controls the value that goes into AES? What does that make the scheme, from her point of view?
Hint: Write down what CBC feeds into AES for the first block.
Answer:
She does. She chooses the plaintext and she knows the IV, so she knows exactly what their XOR will be, which is the block AES encrypts. The randomness that was supposed to make every encryption unique is now something she can plan around.
A cipher whose randomness the attacker can predict is, to that attacker, deterministic. And Part 2 already showed that deterministic schemes lose the CPA game. Nothing about AES was broken; the scheme gave away its only source of surprise.
Concept
The lab turns the CPA game into a small web service, so students can play it with a script. Each piece of the server is one piece of the definition.
| server endpoint | role in the CPA game |
|---|---|
| encrypt a chosen message | the encryption oracle |
| challenge with m0 and m1 | the challenger flips b and returns the encryption of m_b |
| guess b | Mallory's answer; twenty correct in a row earns the flag |
| view the source | Kerckhoffs: the design is public, only the key is secret |
| a session name on every call | keeps one student's IV chain separate from another's |
Twenty correct guesses in a row would happen by luck about once in a million tries, since one half to the power 20 is about 0.00000095. So a flag means a real, repeatable advantage, not a lucky streak. The server's source code is public and the key is random per session: reading the code gives nothing away, which is exactly the principle the course has stressed since the start.
Security I, Lecture 2: Cryptography, part four (when is a cipher secure?) slide s-cpa-ctf
Concept
The hints in the lecture walk through the argument. Here is its logic without the lab solution.
BEAST used this same weakness against real HTTPS. With a browser tricked into sending attacker-influenced requests, it confirmed guesses about a secret cookie and recovered it. The real fix is the lesson: every message needs a fresh IV that nobody can predict, either random or produced by encrypting a counter. That is exactly what TLS 1.1 changed.
| IV rule | predictable before use? | CPA-secure CBC? |
|---|---|---|
| fresh random per message | no | yes |
| encrypt a counter under the key | no | yes |
| last ciphertext block (TLS 1.0) | yes | no |
Security I, Lecture 2: Cryptography, part four (when is a cipher secure?) slide s-cpa-ctf-hint1
Security I, Lecture 2: Cryptography, part four (when is a cipher secure?) slide s-cpa-ctf-hint2
Security I, Lecture 2: Cryptography, part four (when is a cipher secure?) slide s-cpa-ctf-solution
RFC 4346 — The TLS Protocol Version 1.1 (2006), which moved CBC to an explicit per-record IV section 6.2.3.2, CBC block cipher, explicit IV
Sorting
CBC needs an IV that is fresh and unpredictable to the attacker at the time the message is chosen. Sort these choices.
Sort into buckets
Safe or unsafe for CBC?
Error analysis
Three teammates each wrote a helper that encrypts a message with AES-CBC. Open each note to see what a reviewer should say.
Annotate
The pattern to remember: in CBC the IV may be public, but it must not be predictable before it is used. And even a correct IV leaves the integrity gap open.
Real world
BEAST is one case of a general rule: a value meant to be unpredictable is worthless once the attacker can see it coming.
Discussion prompt
Name another place in computing where a value must be unpredictable rather than merely unique, and say what goes wrong if it is predictable.
Hint: Think about tokens that grant access.
Answer:
Session tokens and password-reset links: if they come from a counter or the clock, an attacker can guess someone else's. Anti-CSRF tokens: predictable ones can be forged by another site. TCP initial sequence numbers: predictable ones once let attackers inject packets into other people's connections.
The common thread is the same as for the CBC IV. Unique is enough when the only danger is accidental collision. Unpredictable is required when an adversary benefits from knowing the value in advance. Getting that distinction right is most of what a cryptographic random number generator is for.
Concept
At this point the original lecture paused for four announcements, which are specific to that class: an anonymous feedback form, grading of the first homework and midterm, a note that twelve lab submissions failed validation and are being checked by hand, and a leaderboard for student attacks in the course's practice range, which had already received over fifty submissions.
For anyone working through this deck on their own, the transferable point is about the labs. Each attack lab in this course runs against a server built to be attacked, with permission, and submissions are validated. Practising attacks only on systems you are authorised to test is the habit that separates security work from crime.
Security I, Lecture 2: Cryptography, part four (when is a cipher secure?) slide s-announce-2
Concept
Before combining encryption with a MAC, recall the other mode from last time, because it shows clearly why encryption alone is not enough.
Figure (svg): Counter mode: nonce and counter 0, 1, 2 are each encrypted with AES to give keystream blocks, which are XORed with P1, P2, P3 to give C1, C2, C3
| property | CTR |
|---|---|
| how it works | encrypt nonce and counter to get a keystream, XOR with the plaintext |
| decryption | exactly the same operation |
| padding | none needed |
| parallel | yes, every block is independent |
| the one rule | never reuse a (key, nonce) pair |
Reusing a (key, nonce) pair repeats the keystream, and then C1 XOR C2 equals P1 XOR P2, the one-time-pad reuse problem again. And CTR provides confidentiality only: it gives no integrity at all, which the next slide makes concrete.
Security I, Lecture 2: Cryptography, part four (when is a cipher secure?) slide s-recap-ctr
Fill the middle
Under one key and the same nonce, AES-CTR encrypted rain as de 20 93 49 and shine as df 29 93 49 9e. XOR the first four ciphertext bytes, then compare with rain XOR shin.
Fill in the blanks
de xor df = 01
20 xor 29 = 09
93 xor 93 = 00
49 xor 49 = 00
# 'r','a','i','n' xor 's','h','i','n' = 01 09 00 00
Why: de is 1101 1110 and df is 1101 1111, which XOR to 01. 20 is 0010 0000 and 29 is 0010 1001, which XOR to 09. Equal bytes XOR to 00. The result, 01 09 00 00, is exactly the XOR of the two plaintexts: the keystream cancelled out, so the ciphertexts reveal how the messages relate without any key. That is why a nonce must never repeat under one key.
Prediction
In CTR, each ciphertext bit is a plaintext bit XORed with a keystream bit. Suppose someone on the network flips one ciphertext bit and passes the message on.
Predict first
What does the receiver get after decrypting?
Correct: The original message with exactly the matching plaintext bit flipped, and no warning
Why: Decryption XORs the same keystream back in, so a flipped ciphertext bit becomes the same flipped plaintext bit and nothing else changes. Someone who knows or guesses part of the message can make targeted edits, such as changing an amount, without the key. Encryption hides content but does not stop tampering, which is the job of a MAC.
Section
Two good tools, three ways to bolt them together
Socratic
Encryption gives confidentiality: an eavesdropper learns nothing. A MAC gives integrity: any change breaks the tag. A real channel needs both at once.
Discussion prompt
Before seeing any answer, propose a way to combine an encryption scheme and a MAC. What exactly does your MAC compute its tag over, and in what order does the receiver do things?
Hint: Decide what goes into the MAC: the plaintext or the ciphertext.
Answer:
Figure (svg): Two lanes: the message goes through Encrypt to give a ciphertext Eve learns nothing from; the message goes through MAC to give a tag that breaks if anything changes
There are three natural answers, and all three have been used in real protocols. Encrypt-and-MAC: encrypt the message and MAC the message, send both. MAC-then-Encrypt: MAC the message, then encrypt the message together with its tag. Encrypt-then-MAC: encrypt first, then MAC the ciphertext.
They sound like small variations. They are not. The next slides test each one against the CPA game and against a tampering receiver, and only one survives.
Security I, Lecture 2: Cryptography, part four (when is a cipher secure?) slide s-conf-int
Concept
The obvious idea: run both tools on the message independently. Encrypt the message under one key to get a ciphertext, MAC the message under a second key to get a tag, and send both. SSH's original design did essentially this.
Figure (svg): The message goes into Encrypt with K1 to give C and into MAC with K2 to give a tag computed over the plaintext; both are sent
| part | computed over | sent |
|---|---|---|
| ciphertext C | the plaintext, with fresh randomness | yes |
| tag | the plaintext | yes, in the clear |
It looks airtight: the ciphertext hides the message and the tag proves it was not changed. Before the next slide, ask yourself one question about the tag: is a MAC randomized or deterministic?
Security I, Lecture 2: Cryptography, part four (when is a cipher secure?) slide s-enc-mac-wrong
Prediction
A MAC is deterministic: the same key and message always produce the same tag. In Encrypt-and-MAC the tag is computed over the plaintext and sent in the clear.
Predict first
What can an eavesdropper learn from the tags alone?
Correct: Whether two messages are the same, since equal messages give equal tags
Why: She cannot compute or forge tags, but she can compare them. Two equal messages always carry equal tags, even though their ciphertexts differ. That is exactly the equality leak from the weather station, smuggled back in through the tag.
Concept
Here is the leak on real values. The same message is sent twice; the ciphertexts differ because CTR uses a fresh nonce, but the tags are identical.
send 1: C = de209349 tag = HMAC(K2, "rain") = 5c7faa41df2518c6...
send 2: C = d78e0aa2 tag = HMAC(K2, "rain") = 5c7faa41df2518c6...
send 3: C = ........ tag = HMAC(K2, "shine") = 70d8cc7585797130...| send | ciphertext | tag | eavesdropper learns |
|---|---|---|---|
| 1, rain | de209349 | 5c7faa41... | a new message |
| 2, rain | d78e0aa2 | 5c7faa41... | same as send 1 |
| 3, shine | different | 70d8cc75... | different from 1 and 2 |
In game terms: Mallory asks the oracle to encrypt m0 and keeps its tag. In the challenge, the tag equals that kept tag exactly when the challenger encrypted m0. She is right every round, so Encrypt-and-MAC is not CPA-secure, even though the encryption inside it is.
Security I, Lecture 2: Cryptography, part four (when is a cipher secure?) slide s-enc-mac-break
Faded example
The game argument is the same shape as the one against deterministic encryption. Fill in the comparison and the answers.
Fill in the blanks
C0, tag0 = oracle(m0) # keep the tag
C, tag = challenge(m0, m1)
if tag == tag0:
guess = 0
else:
guess = 1
Why: The MAC is a deterministic function of the plaintext, so the challenge tag equals tag0 exactly when the challenger encrypted m0. The ciphertext plays no part; the tag alone decides. Root cause: the tag is computed over the plaintext and sent where everyone can see it.
Concept
Fix attempt 1 by hiding the tag: MAC the message first, then encrypt the message together with its tag. SSL and TLS up to version 1.2 did this with CBC. The equality leak is gone, because the tag is now inside the ciphertext.
Figure (svg): Sender: message, MAC, message plus tag, Encrypt, ciphertext. Receiver: ciphertext, Decrypt, strip padding, check tag, with decryption and padding work done on unverified bytes
| receiver step | what it is working on |
|---|---|
| 1. decrypt | bytes from the network that nobody has verified |
| 2. strip the padding | still unverified |
| 3. check the tag | only now is anything verified |
The trouble is the receiver. It cannot check the tag without decrypting first, so it must open the envelope before it checks the seal. Every step before the tag check runs on bytes an attacker may have crafted.
Security I, Lecture 2: Cryptography, part four (when is a cipher secure?) slide s-mac-then-enc
Socratic
In MAC-then-Encrypt with CBC, a tampered message can fail in two different places: the padding check, or the tag check.
Discussion prompt
Suppose the receiver replies bad padding in one case and bad MAC in the other. Conceptually, what does each reply tell someone who sent a deliberately altered ciphertext? Why is that dangerous even though the message is rejected either way?
Hint: The server's choice of error message depends on the decrypted plaintext.
Answer:
Each reply says whether the decrypted bytes of the altered message happened to have valid padding. That is one small fact about plaintext the attacker cannot see. The message is rejected in both cases, but the reason for rejection leaks information.
One bit sounds harmless. But the attacker can send many altered messages, and each answer is a new fact about the hidden plaintext. Collected systematically, those facts add up to the whole message, without the key. A server that answers questions about unverified plaintext is called an oracle, and this kind is a padding oracle. The lecture's CBC lab from part three was exactly this bug.
Concept
This is not a hypothetical. MAC-then-Encrypt with CBC produced a decade of practical attacks on SSL and TLS, each one a variation on the receiver revealing something before verification.
| year | attack | what leaked |
|---|---|---|
| 2002 | Vaudenay's padding oracle | different error messages for bad padding and bad MAC |
| 2013 | Lucky Thirteen | timing alone: identical errors, slightly different processing time |
| 2014 | POODLE | SSL 3.0 padding that was not checked at all |
On the theory side, Krawczyk proved in 2001 that MAC-then-Encrypt is not secure in general: it is safe only with particular ciphers used in particular ways, which is a fragile thing to depend on. Lucky Thirteen shows how fragile. Making the error messages identical was the standard patch, and it still leaked through timing.
An analogy: a safe that beeps differently for a wrong first digit and a wrong second digit can be opened one digit at a time. MAC-then-Encrypt keeps building safes like that, because it does work on secret data before it knows whether the input is genuine.
Security I, Lecture 2: Cryptography, part four (when is a cipher secure?) slide s-mac-then-enc
Krawczyk — The Order of Encryption and Authentication for Protecting Communications (CRYPTO 2001) the order of encryption and authentication
Two truths and a lie
Three claims about the second attempt. Two are true.
Eliminate the wrong options
Which claim is the myth?
Survives elimination: m2
Why: Identical messages hide one channel, not all of them. Lucky Thirteen recovered plaintext from TLS purely from differences in processing time. The real problem is structural: any work done on unverified input can leak. The fix is to change the order so that verification comes first.
Concept
Change what the MAC covers. Encrypt the message under K1 to get a ciphertext, then compute the tag over the ciphertext under a separate key K2. Send both.
Figure (svg): Sender: message, Encrypt with K1, ciphertext, MAC with K2 over the ciphertext, send ciphertext and tag. Receiver: recompute the MAC over the ciphertext, compare tags, and only then decrypt
| problem | how Encrypt-then-MAC avoids it |
|---|---|
| tag leaks equality (attempt 1) | the tag is over random-looking ciphertext, so equal messages give unrelated tags |
| work on unverified bytes (attempt 2) | the receiver checks the tag first and never decrypts a forgery |
| one key used for two jobs | separate keys K1 and K2 |
Bellare and Namprempre proved in 2000 that this order is secure for any CPA-secure cipher combined with any secure MAC. It is the generic composition that always works, which is why the course recommends it whenever encryption and a MAC are assembled by hand.
Security I, Lecture 2: Cryptography, part four (when is a cipher secure?) slide s-enc-mac
Bellare and Namprempre — Authenticated Encryption: Relations among Notions and Analysis of the Generic Composition Paradigm (ASIACRYPT 2000) generic composition, Encrypt-then-MAC
Concept
Here is the construction in code, and the effect on the two rain messages from before. The tag now covers the nonce and the ciphertext, which change every time.
nonce = os.urandom(8)
C = aes_ctr(K1, nonce, msg)
tag = hmac.new(K2, nonce + C, hashlib.sha256).digest()
send(nonce, C, tag)| send | ciphertext | Encrypt-and-MAC tag | Encrypt-then-MAC tag |
|---|---|---|---|
| 1, rain | de209349 | 5c7faa41... | 7957a467... |
| 2, rain | d78e0aa2 | 5c7faa41... | 4a336a21... |
| what an eavesdropper sees | unrelated | equal: leak | unrelated: no leak |
Notice that the nonce goes into the MAC as well. Anything the receiver will use to decrypt must be covered by the tag, otherwise an attacker could swap the nonce and the receiver would decrypt with the wrong keystream without noticing.
Security I, Lecture 2: Cryptography, part four (when is a cipher secure?) slide s-enc-mac
Trade off
Fill in the blanks to compare the three ways of combining encryption with a MAC.
Comparison matrix
| Encrypt-and-MAC | MAC-then-Encrypt | Encrypt-then-MAC | |
|---|---|---|---|
| MAC computed over | plaintext | plaintext | ciphertext |
| tag leaks equality? | yes | no | no |
| verify before decrypting? | no | no | yes |
| secure in general? | no | no | yes |
Only Encrypt-then-MAC both hides equality and lets the receiver reject forgeries before touching the cipher. The two failures fail for different reasons: one leaks through what the tag covers, the other through the order the receiver works in.
Ranking
Put the receiver's steps in the safe order.
Put in order
Why: Verification comes before any use of K1, so a forged or altered message never reaches the decryption code, and there is nothing secret for an error message or a timing difference to reveal. The constant-time comparison stops the check itself from leaking how many tag bytes matched.
Error analysis
A teammate implemented Encrypt-then-MAC. The sender is right; the receiver below is not. Open each note.
Annotate
Every one of these mistakes has appeared in real code. That is the strongest argument for the next slide: do not assemble this yourself.
Concept
Real systems rarely hand-assemble Encrypt-then-MAC. They use authenticated encryption with associated data, AEAD: a single primitive that encrypts and authenticates correctly in one call. AES-GCM and ChaCha20-Poly1305 are the standard choices, and TLS 1.3 allows nothing else.
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
key = AESGCM.generate_key(bit_length=128)
nonce = os.urandom(12) # never reuse with this key
ct = AESGCM(key).encrypt(nonce, b"rain", b"hdr")
pt = AESGCM(key).decrypt(nonce, ct, b"hdr") # InvalidTag if anything changed| piece | what it is |
|---|---|
| key | 16 random bytes for AES-128-GCM |
| nonce | 12 bytes, must never repeat under one key |
| associated data hdr | authenticated but not encrypted, such as a packet header |
| ct | ciphertext plus a 16-byte tag: 4 + 16 = 20 bytes for rain |
| decrypt | verifies first; raises InvalidTag and returns nothing if anything changed |
AEAD bakes in every lesson of this part: the tag covers the ciphertext and the header, verification happens before any plaintext is released, and there is one key and one call to get right. The one rule left to you is the nonce: never reuse one under the same key.
pyca/cryptography documentation — AESGCM authenticated encryption AESGCM
Security I, Lecture 2: Cryptography, part four (when is a cipher secure?) slide s-enc-mac
Missing information
A teammate says: we switched to AES-GCM, so confidentiality and integrity are both handled.
Discussion prompt
What would you still need to know before agreeing? List the questions you would ask.
Hint: Think about the nonce, the key, and what AEAD does not promise.
Answer:
How are nonces generated? GCM fails badly on nonce reuse: it leaks the XOR of plaintexts, as CTR does, and also lets an attacker forge tags. Random 12-byte nonces are fine for a moderate number of messages per key; a counter that survives restarts is better for high volume.
Where do keys come from, and are they ever reused across purposes? Is everything that matters inside the authenticated data, such as the message type, sender and sequence number? And what stops an old valid message being replayed? AEAD does not provide freshness on its own, just as a MAC does not.
Pattern
Every scheme in this lesson can be judged with the same four questions, asked in order.
| design | fails at question |
|---|---|
| AES-ECB, or CBC with a zero IV | 1 |
| CBC with a chained IV (TLS 1.0) | 2 |
| CTR with a fresh nonce, no MAC | 3 |
| Encrypt-and-MAC, MAC-then-Encrypt | 4 |
| Encrypt-then-MAC, or AES-GCM with unique nonces | passes all four |
Check
Solve it on paper before you click.
Check your understanding
You must build a secure channel from AES-CTR and HMAC-SHA256 by hand. Which design is correct?
Answer: C
Why: Encrypt-then-MAC with separate keys, with the nonce covered by the tag and verification before decryption. It is the composition proven secure for any CPA-secure cipher and secure MAC.
Check
Solve it on paper before you click.
Check your understanding
Which scheme is CPA-secure, assuming AES is a secure block cipher?
Answer: C
Why: CPA security needs encryption whose randomness the attacker cannot predict when choosing messages. A fresh random IV provides that. ECB and a zero IV are deterministic, and a chained IV is known before it is used, the TLS 1.0 bug.
Connect it up
Pull the lesson together in one diagram.
Draw it
Draw the CPA game with its oracle, challenge and guess. Beside it, show the three ways to combine encryption and a MAC as small pipelines. Mark on each pipeline where it fails or why it succeeds: the equality leak, decrypt-before-verify, or verify-first over the ciphertext. Add one note about IVs and nonces.
A complete picture links the two halves: the CPA game explains why randomness must be fresh and unpredictable, and the same game shows that a deterministic tag over the plaintext leaks. The safe pipeline encrypts, MACs the ciphertext and nonce with a separate key, and verifies first, which is what AEAD does in one call.
Exit ticket
One question to check the main idea stuck.
Predict first
Why does every deterministic encryption scheme fail the CPA game?
Correct: Because the attacker can ask the oracle to encrypt m0 and compare it with the challenge ciphertext
Why: Deterministic means the same message always gives the same ciphertext, so the challenge matches the oracle's encryption of m0 exactly when b is 0. That one comparison wins every round, regardless of how strong the block cipher is, which is why encryption must use a fresh, unpredictable IV or nonce.
Recap
The lesson's single thread: secure means winning a guessing game no better than chance; that forces encryption to be randomized with values the attacker cannot predict; and when encryption meets a MAC, the MAC must cover the ciphertext and be checked first.
| you need | use |
|---|---|
| confidentiality against chosen plaintexts | randomized encryption with a fresh, unpredictable IV or nonce |
| confidentiality and integrity, built by hand | Encrypt-then-MAC, separate keys, verify first |
| confidentiality and integrity, in practice | an AEAD mode such as AES-GCM or ChaCha20-Poly1305 |
Bellare and Namprempre — Authenticated Encryption: Relations among Notions and Analysis of the Generic Composition Paradigm (ASIACRYPT 2000) generic composition
Want this taught 1-on-1? Alexander tutors Computer Security — $55/session, free consultation.