এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।
University Computer Science — Year 3 · স্নাতক তৃতীয় বর্ষ
27Symmetric Cryptography and Hash Functions
Two parties who share a secret key want to talk over a network that anyone can read and anyone can tamper with. This chapter says first what “secure” should mean, proves that perfect secrecy exists and costs a key as long as the message, and then builds, from the published standards, the tools that real systems use instead: the block cipher AES and the ways to chain it, the stream cipher ChaCha20, the hash function SHA-256, and the message authentication codes that detect tampering. Every one is checked against its standard’s test vectors, and every misuse that the chapter shows, a reused key, a padding error message, a naive authentication tag, is an attack on the chapter’s own toy services, followed by its fix. The programs are written to be read.
In practice — Use a vetted library
A real system never runs code like this chapter’s. It calls a vetted library, whose code has been reviewed for years, runs in constant time and is patched when an attack appears; Python’s own hashlib, hmac and secrets cover hashing, MACs and key generation. The chapter’s implementations are for understanding, and they are checked against the standards so that what they show is true.
You already know
A cipher turns a plaintext into a ciphertext with a key; frequency analysis breaks a substitution cipher by counting letters (grade 9 volume), and a computer encrypts with standard ciphers and checks data with hash functions (grade 12 volume). XOR, , adds bits modulo 2, so . In the mathematics books, the bytes form the finite field , polynomials over modulo an irreducible one of degree 8, where every non-zero element has an inverse; and among 23 people, two share a birthday more often than not.
27.1 What “secure” means
Definition 27.1 (Kerckhoffs’s principle, attack model, perfect secrecy, computational security, indistinguishability)
Kerckhoffs’s principle asks a cipher to stay secure when everything about it except the key is public. An attack model says what the attacker may do: see ciphertexts only; know some plaintexts and their ciphertexts; have plaintexts of its choice encrypted (chosen plaintext); or also have ciphertexts of its choice decrypted (chosen ciphertext). A cipher has perfect secrecy if, for a key chosen uniformly, every ciphertext is equally likely whatever the plaintext: for all , , . It has computational security if no attacker with a realistic amount of computation succeeds with more than a negligible probability. Indistinguishability is the game that makes this precise: the attacker chooses two messages , of the same length, receives the encryption of one of them, chosen by a fair coin, may go on using its attack model, and must guess which; the cipher is secure if no efficient attacker guesses right with probability noticeably above .
Kerckhoffs stated the principle in an article of 1883; Shannon, who put secrecy on a mathematical footing in 1949, phrased it as “the enemy knows the system”. A secret algorithm is found out sooner or later, by a stolen device or a leaked program; a key can be changed in a minute.
Definition 27.2 (One-time pad)
The one-time pad encrypts an -byte message with a uniformly random -byte key , used for one message only: , and .
Theorem 27.3 (Shannon’s secrecy theorem)
The one-time pad has perfect secrecy. Conversely, a cipher with perfect secrecy has at least as many keys as messages.
Proof. For the pad, given and , exactly one key gives , namely , so , the same for every . Conversely, take a ciphertext that occurs, from some message and some key. By perfect secrecy, for every message , so for each some key encrypts to . Decryption with a key is a function of , so one key cannot decrypt to two different messages: these keys are all different, and there are at least as many keys as messages. ∎
The price is a key as long as everything ever sent, delivered in advance and never reused. Reuse is fatal: if and , then , the key is gone, and a guessed word in one message reveals the other at the same place.
"""otp.py -- the one-time pad, and what happens when its key is used twice."""
import random
def xor(a, b):
return bytes(x ^ y for x, y in zip(a, b))
rng = random.Random(27) # a fixed seed so the run repeats; a real pad uses secrets
m1 = b"MEET AT THE LIBRARY AT NOON"
m2 = b"THE KEY IS UNDER THE MAT "
key = rng.randbytes(len(m1))
c1, c2 = xor(m1, key), xor(m2, key)
print("c1:", c1.hex())
print("decrypted:", xor(c1, key).decode())
fake = b"STAY HOME, THE PLAN IS OFF " # any 27 bytes: some key gives them
print("the key", xor(c1, fake).hex(), "decrypts c1 to", xor(c1, xor(c1, fake)).decode())
x = xor(c1, c2)
print("c1 xor c2 = m1 xor m2:", x.hex(), x == xor(m1, m2))
for guess in (b"THE ", b"LIBRARY"): # guess a word of m1 at every position
for i in range(len(x) - len(guess) + 1):
piece = xor(x[i : i + len(guess)], guess)
if all(65 <= b <= 90 or b == 32 for b in piece):
print(
f"m1 has {guess.decode()!r} at {i:>2}? then m2 has {piece.decode()!r}"
)
$ python otp.py
c1: acac46f250cb8d5a0ebcc993a680b514005a58d534e2150736087c
decrypted: MEET AT THE LIBRARY AT NOON
the key fff807ab7083c2174b90e9c7eec595444c1b16f57db13548704e5c decrypts c1 to STAY HOME, THE PLAN IS OFF
c1 xor c2 = m1 xor m2: 190d00746b040d001d1b6575020d0700610611656119611a6f6f6e True
m1 has 'THE ' at 0? then m2 has 'MEET'
m1 has 'THE ' at 8? then m2 has 'IS U'
m1 has 'THE ' at 12? then m2 has 'VEB '
m1 has 'THE ' at 13? then m2 has 'YOEA'
m1 has 'THE ' at 17? then m2 has 'RY A'
m1 has 'LIBRARY' at 12? then m2 has 'NDER TH'
The key here comes from random with a seed, so that the run repeats. Python’s documentation says that random is designed for modelling and simulation, and that real keys come from secrets. The rest of the chapter gives up perfect secrecy for computational security: a 16-byte key that encrypts gigabytes, secure as long as no one can do much better than trying the keys.
27.2 Block ciphers and their modes
Definition 27.4 (Block cipher, round key, AES)
A block cipher is a family of permutations of the -bit blocks, one for each key, , with an inverse that is efficient to compute when is known. Most are built from rounds, each mixing the block with a round key derived from the key. AES is the block cipher of the standard FIPS 197: 16-byte blocks, keys of 16, 24 or 32 bytes, and 10, 12 or 14 rounds.
AES treats the block as a array of bytes. Each round applies four steps: SubBytes replaces every byte by its inverse in followed by a fixed affine map, the only non-linear step; ShiftRows rotates row by places; MixColumns multiplies every column by a fixed matrix over , so that each output byte depends on the whole column; AddRoundKey XORs the round key. Two rounds of ShiftRows and MixColumns already make every byte of the state depend on every byte of the input.
def encrypt_block(key, block):
k = round_keys(key)
s = add_round_key(list(block), k[0])
for r in range(1, 11):
s = shift_rows(sub_bytes(s))
if r < 10: # the last round has no MixColumns
s = mix_columns(s)
s = add_round_key(s, k[r])
return bytes(s)
$ python aes_vector.py
S-box of 00, 01, 53: 63 7c ed
round key 1: a0fafe1788542cb123a339392a6c7605
round key 10: d014f9a8c9ee2589e13f0cc8b6630ca6
ciphertext: 3925841d02dc09fbdc118597196a0b32
FIPS 197: 3925841d02dc09fbdc118597196a0b32
decrypts back: True
A block cipher encrypts 16 bytes. A message is longer, and its length is rarely a multiple of 16.
Definition 27.5 (Mode of operation, ECB, CBC, initialisation vector, padding, CTR, padding oracle)
A mode of operation encrypts a message of several blocks with a block cipher. ECB mode encrypts each block alone: . CBC mode chains them: , starting from , an initialisation vector (IV) that must be unpredictable and is sent with the ciphertext; decryption computes . Padding extends the message to a whole number of blocks; PKCS#7 padding adds bytes of value , , and is checked and removed after decryption. CTR mode turns the block cipher into a stream cipher: , with a counter block that must never repeat under one key. A padding oracle is any way for an attacker to learn whether the padding of a ciphertext of its choice was valid.
NIST’s SP 800-38A defines ECB, CBC and CTR, among five modes, with test vectors that the chapter’s tests check. ECB is a code book: equal plaintext blocks give equal ciphertext blocks. A picture shows it. The program below draws a ring and a bar, one byte per pixel, and encrypts it in both modes.
$ python ecb_pattern.py
plain 384 blocks, 41 different
ECB 384 blocks, 41 different
CBC 384 blocks, 384 different
figures/ecb.dat, encrypted with AES-128. In ECB each run of 16 equal pixels becomes the same 16 bytes, and the shapes stay visible; in CBC the ciphertext looks random.def cbc_encrypt(key, iv, m):
out, prev = [], iv
for p in blocks(m):
prev = encrypt_block(key, xor(p, prev)) # C_i = E(P_i xor C_i-1), C_0 = IV
out.append(prev)
return b"".join(out)
CBC hides patterns but not errors. The receiver decrypts, then checks the padding, and a service that answers differently to bad padding than to other errors gives the attacker one bit per query: is the last byte of a valid padding, for a forged block of the attacker’s choice? Vaudenay described in 2002 how this bit decrypts the whole message. The attacker changes the last byte of until the padding is valid: then the last byte of is 01, which gives the last byte of , and XORed with the real previous block, the plaintext’s. Then it aims for 02 02, and so on, at most 256 queries per byte.
def attack_block(oracle, prev, block):
"""Find D(block) byte by byte from the end, by forging the block before it."""
d = bytearray(16) # D(block), the block cipher's output before the XOR
for k in range(1, 17): # make the last k bytes decrypt to the padding k
for guess in range(256):
fake = bytearray(16)
for j in range(16 - k + 1, 16):
fake[j] = d[j] ^ k
fake[16 - k] = guess
if oracle(bytes(fake), block):
if k == 1: # rule out a longer padding that happened to be valid
fake[14] ^= 1
if not oracle(bytes(fake), block):
continue
d[16 - k] = guess ^ k
break
return bytes(x ^ y for x, y in zip(d, prev))
$ python padding_oracle.py
ciphertext: 48 bytes; attack made 6,389 queries
recovered: b'LOAN 42 TO READER 7 UNTIL 2026-12-01'
against encrypt-then-MAC: 12,288 queries, all refused
bytes 'recovered': c509bc1015ac2041e78802d3bfd9208a ... noise
The fix is not a better error message but authentication: a service that rejects every ciphertext it did not produce, before decrypting it, has nothing to leak. The last section builds it.
27.3 Stream ciphers
Definition 27.6 (Stream cipher, keystream, nonce)
A stream cipher expands a short key into a long pseudo-random keystream and XORs it with the message, as a one-time pad with a computed key. A nonce (number used once) is an input that makes the keystream differ from message to message under the same key; a nonce must never be reused with the same key.
A reused nonce is a reused pad, with the leak of Output 27.1. ChaCha20, designed by Bernstein and specified in RFC 8439, makes 64 bytes of keystream from a 32-byte key, a 32-bit block counter and a 12-byte nonce. Its state is sixteen 32-bit words: four constants, the key, the counter and the nonce. Twenty rounds of additions, XORs and rotations mix them, and the initial state is added back at the end, so that the rounds cannot simply be run backwards from the output.
def quarter_round(s, a, b, c, d):
s[a] = (s[a] + s[b]) & M
s[d] = rotl(s[d] ^ s[a], 16)
s[c] = (s[c] + s[d]) & M
s[b] = rotl(s[b] ^ s[c], 12)
s[a] = (s[a] + s[b]) & M
s[d] = rotl(s[d] ^ s[a], 8)
s[c] = (s[c] + s[d]) & M
s[b] = rotl(s[b] ^ s[c], 7)
def block(key, counter, nonce):
"""64 bytes of keystream from a 32-byte key, a 32-bit counter, a 12-byte nonce."""
const = (0x61707865, 0x3320646E, 0x79622D32, 0x6B206574) # "expand 32-byte k"
init = [*const, *struct.unpack("<8L", key), counter, *struct.unpack("<3L", nonce)]
s = init.copy()
for _ in range(10): # 20 rounds: a column round and a diagonal round, ten times
for q in (
(0, 4, 8, 12),
(1, 5, 9, 13),
(2, 6, 10, 14),
(3, 7, 11, 15),
(0, 5, 10, 15),
(1, 6, 11, 12),
(2, 7, 8, 13),
(3, 4, 9, 14),
):
quarter_round(s, *q)
return struct.pack("<16L", *((x + y) & M for x, y in zip(s, init)))
$ python chacha20.py
block 2.3.2: 10f1e7e4d13b5915500fdd1fa32071c4 ... True
cipher 2.4.2: 6e2e359a2568f98041ba0728dd0d6981 ... True
ChaCha20 uses only additions, XORs and rotations of words, which take the same time whatever their values; table look-ups such as AES’s S-box can take a time that depends on the key through the cache, and RFC 8439 notes that many AES implementations are open to such timing attacks.
27.4 Hash functions
Definition 27.7 (Cryptographic hash function, preimage resistance, second-preimage resistance, collision resistance)
A cryptographic hash function maps messages of any length to a fixed-length digest, computed by a public algorithm, with no key. It has preimage resistance if, given a digest , finding any with is infeasible; second-preimage resistance if, given , finding with is infeasible; and collision resistance if finding any two different messages with the same digest is infeasible.
A hash table needs a hash function that spreads keys well; a cryptographic one must also resist an adversary who chooses the inputs (Year 1 volume). Collisions exist, since there are more messages than digests; resistance means they are hard to find. And they are easier to find than preimages, by the same count that makes shared birthdays common.
Theorem 27.8 (Birthday bound)
Draw values independently and uniformly from a set of . The probability that all are different is at most . So draws give a collision with probability at least .
Proof. Facts used: for every real . The -th draw, , avoids the earlier values, all different, with probability , so
This is at most as soon as , which holds for . ∎
A finer computation gives the mean number of draws until the first collision, about . A digest of bits therefore resists collisions for only about work: the 256 bits of SHA-256 give . The weekend problem measures the bound on a 32-bit digest.
Definition 27.9 (Merkle–Damgård construction, length-extension attack)
The Merkle–Damgård construction hashes a message by padding it to whole blocks, with its length in the last one, and running a compression function along the blocks: is a fixed initial value, , and the digest is . A length-extension attack uses and the length of , without , to compute for any , by continuing the chain from .
SHA-256, from FIPS 180-4, is a Merkle–Damgård construction with 64-byte blocks and a 32-byte state. Its 64 round constants are the first 32 bits of the fractional parts of the cube roots of the first 64 primes, and its initial value comes from the square roots of the first 8: numbers anyone can recompute, rather than numbers the designers picked.
def compress(h, chunk):
w = list(struct.unpack(">16L", chunk))
for t in range(16, 64):
s0 = rotr(w[t - 15], 7) ^ rotr(w[t - 15], 18) ^ w[t - 15] >> 3
s1 = rotr(w[t - 2], 17) ^ rotr(w[t - 2], 19) ^ w[t - 2] >> 10
w.append((w[t - 16] + s0 + w[t - 7] + s1) & M)
a, b, c, d, e, f, g, hh = h
for t in range(64):
t1 = (
hh
+ (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25))
+ (e & f ^ ~e & g)
+ K[t]
+ w[t]
)
t2 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + (a & b ^ a & c ^ b & c)
a, b, c, d, e, f, g, hh = (t1 + t2) & M, a, b, c, (d + t1) & M, e, f, g
return [(x + y) & M for x, y in zip(h, (a, b, c, d, e, f, g, hh))]
$ python sha256_check.py
K[0], K[63]: 428a2f98 c67178f2 H0[0]: 6a09e667
SHA-256("abc") = ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
equal to hashlib on 1000 of 1000 random messages of 0 to 299 bytes
a message of 55 bytes is padded to 64 bytes
a message of 56 bytes is padded to 128 bytes
a message of 64 bytes is padded to 128 bytes
hashlib on 1,000 random messages. A message of 56 bytes needs a second block: its 8-byte length no longer fits.27.5 Message authentication
Definition 27.10 (Message authentication code, HMAC, authenticated encryption, AEAD)
A message authentication code (MAC) computes, from a key and a message, a tag that no one without the key can compute for a new message, even after seeing the tags of messages of its choice. HMAC is the MAC of RFC 2104 built from a hash function with blocks of bytes: , where the key is padded with zeros to bytes and , are the bytes 0x36 and 0x5C repeated times. Authenticated encryption gives both secrecy and integrity: the receiver either gets the plaintext or learns that the ciphertext was changed. AEAD (authenticated encryption with associated data) also authenticates data sent in the clear, such as a header.
The tempting MAC falls to length extension. A toy library service authorises loans with such tags:
order = b"reader=r7&book=42&days=14"
tag = naive_tag(order)
print("order:", order.decode(), " tag:", tag.hex()[:16], "...")
# The attacker knows the order, the tag and the key's length, 16 bytes; it continues
# the hash from the tag, which is the state after key || order || padding.
glue = pad(16 + len(order))
extra = b"&days=365"
state = struct.unpack(">8L", tag)
forged_tag = sha256(extra, state, done=16 + len(order) + len(glue))
forged = order + glue + extra
print("forged order:", forged)
print("accepted by the naive service:", naive_tag(forged) == forged_tag)
$ python length_ext.py
order: reader=r7&book=42&days=14 tag: daf1fa466be78fb7 ...
forged order: b'reader=r7&book=42&days=14\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01H&days=365'
accepted by the naive service: True
same trick against HMAC accepted: False
&days=365 and is accepted. A service that parses the last days field lends the book for a year. Against HMAC the same continuation fails.HMAC resists because its tag is the hash of the inner digest under a second key-dependent block: continuing the outer chain from the tag would extend a message the service never hashes, and the inner digest of the extended message is hidden inside the outer hash (exercise 27.11). A tag must also be compared in constant time, with hmac.compare_digest, since a comparison that stops at the first wrong byte tells a patient attacker how many bytes it got right.
To combine encryption and a MAC, Bellare and Namprempre compared three orders in 2000 and proved that encrypting first and then computing the MAC over the ciphertext resists chosen-ciphertext attacks whenever the cipher and the MAC meet minimal requirements; the receiver then checks the tag before decrypting anything, and the padding oracle disappears. RFC 8439 defines such a scheme: ChaCha20 encrypts, and Poly1305, a one-time authenticator keyed by the first keystream block of the nonce, authenticates the associated data and the ciphertext.
def tag(key, nonce, aad, c):
otk = block(key, 0, nonce)[:32] # a fresh one-time Poly1305 key per nonce
lengths = len(aad).to_bytes(8, "little") + len(c).to_bytes(8, "little")
return poly1305(otk, pad16(aad) + pad16(c) + lengths)
def seal(key, nonce, aad, plain):
c = chacha20(key, 1, nonce, plain) # encrypt, then authenticate the ciphertext
return c, tag(key, nonce, aad, c)
def open_(key, nonce, aad, c, t):
if tag(key, nonce, aad, c) != t: # check before decrypting anything
raise ValueError("authentication failed")
return chacha20(key, 1, nonce, c)
$ python aead.py
ciphertext starts d31a8d34648e60db7b86afbc53ef7ec2 True
tag 1ae10b594f09e26a7e902ecbd0600691 True
opens to Ladies and Gentlemen of the class of '99: ...
one bit flipped: authentication failed
27.6 Exercises
Exercise 27.1 ★
A one-time pad on bytes encrypts the message 1011 0110 with the key 0110 1100. Give the ciphertext, and the key that would make the same ciphertext decrypt to 0000 1111.
Solution
Solution of Exercise 27.1.
. The key that decrypts this ciphertext to is the XOR of the two: . Every 8-bit message has such a key, which is why the ciphertext alone says nothing.
Exercise 27.2 ★
A message of four blocks has . In which of ECB, CBC and CTR is ? Under a fixed key, the same message is encrypted twice: in which modes are the two ciphertexts equal, if the IV or the counter is chosen afresh each time, and if it is reused?
Solution
Solution of Exercise 27.2.
Only in ECB: . In CBC the inputs and differ unless , which happens with probability ; in CTR the keystream blocks of counters and differ, since is a permutation. Encrypting the same message twice: ECB always gives the same ciphertext; CBC and CTR give different ones with a fresh IV or counter, and the same one when it is reused. In CTR a reused counter is worse than repetition: two different messages then leak their XOR.
Exercise 27.3 ★
How many 64-bit digests must be drawn, by the birthday bound, for a collision to be more likely than not? About how many on average until the first? How long would a machine computing digests per second take?
Solution
Solution of Exercise 27.3.
With , Theorem 27.8 gives a collision with probability at least after digests, and the mean is . At digests per second, about five seconds. A 64-bit digest offers no collision resistance against a computer.
Exercise 27.4 ★
Without running it, say what the line c1 xor c2 = m1 xor m2 of Output 27.1 contains at the positions where and have the same letter, and at the positions where one has a space and the other a capital letter.
Solution
Solution of Exercise 27.4.
The line is , byte by byte. Where both messages have the same letter, the byte is 00: position 2 (E and E) gives the third byte, 00. A space is 0x20 and a capital letter lies between 0x41 and 0x5a; their XOR flips bit 5 of the letter and lands between 0x61 and 0x7a, the lower-case letters: position 3, a T against a space, gives 74, the code of t. This is why crib dragging works: the XOR of two texts is full of such recognisable bytes.
Exercise 27.5 ★★
encrypt_buggy in exercises/ex5_ctr_bug.py encrypts every message in CTR mode from the counter block 0. Show what an eavesdropper learns from two messages, then fix it with an 8-byte nonce per message in the first half of the counter block, sent with the ciphertext. How many messages, and how long, can one key then encrypt?
Solution
Solution of Exercise 27.5.
Two messages encrypted from counter 0 use the same keystream, so , as the first line of the program’s output shows, and the attack of Output 27.1 applies. The fix puts an 8-byte nonce in the first half of the counter block and the block number in the second, and sends the nonce in front of the ciphertext. Two different nonces give counter blocks that never meet, so no keystream block repeats. One key then encrypts up to messages, each of up to blocks, bytes, if the nonce is a counter. A random nonce collides after about messages by the birthday bound, so a counter, or a longer nonce, is the safer choice.
Exercise 27.6 ★★
Write cbc_decrypt_checked(key, iv, c) from the definition of CBC and of PKCS#7 padding, using only decrypt_block. It must refuse an empty ciphertext, a length that is not a multiple of 16, and a bad padding. Test it on the vector F.2.1 of SP 800-38A.
Solution
Solution of Exercise 27.6.
exercises/ex6_cbc.py: refuse unless the IV has 16 bytes and the ciphertext is non-empty with a length divisible by 16; then with the IV; read from the last byte, and refuse unless and the last bytes all equal . The test encrypts the four plaintext blocks of SP 800-38A F.2.1 followed by a full padding block, decrypts, and gets them back; it checks that the vector’s own ciphertext, whose last plaintext byte 0x10 would mean sixteen bytes of padding that are not there, is refused, as are a 15-byte and an empty ciphertext. A real service must give the same answer for every kind of refusal, or this function becomes a padding oracle.
Exercise 27.7 ★★
A letter-level one-time pad shifts each letter of the message by a key letter, modulo 26. Prove that it has perfect secrecy when the key letters are independent and uniform. Then prove that the Vigenère cipher, which repeats a key of length , does not, for messages longer than .
Solution
Solution of Exercise 27.7.
Facts used: for fixed and in , exactly one satisfies . For a message of letters and independent uniform key letters, a ciphertext arises from only with the key , of probability , the same for every : perfect secrecy. For Vigenère with a key of length , take messages of length : letters 1 and use the same key letter, so . For , every ciphertext has ; for , none does. So depends on . The converse of Theorem 27.3 gives the same answer by counting: keys against messages. A test enumerates both cases for .
Exercise 27.8 ★★
Prove that uniform draws from values collide with probability at most . Together with Theorem 27.8, what do the two bounds say about ?
Solution
Solution of Exercise 27.8.
Facts used: . A collision means for some pair . Each of the pairs collides with probability , so . For this upper bound is about , and the theorem’s lower bound is about . So draws collide with probability between 0.39 and 0.5: the collision threshold is , up to a constant factor. A test checks the upper bound by simulation for , .
Exercise 27.9 ★★
With PKCS#7 padding and 16-byte blocks, how many blocks and padding bytes do messages of 0, 1, 15, 16, 17 and 100 bytes produce? Why must a message of exactly 16 bytes get a whole block of padding?
Solution
Solution of Exercise 27.9.
Lengths 0, 1, 15, 16, 17, 100 give 1, 1, 1, 2, 2 and 7 blocks, with 16, 15, 1, 16, 15 and 12 padding bytes: always bytes, never 0. A message of 16 bytes ending in 01 would otherwise be read, after decryption, as 15 bytes plus one byte of padding. Padding must be removable without knowing the length, so every message gets at least one padding byte, and one already a whole number of blocks gets a full block.
Exercise 27.10 ★★★
A service encrypts in CBC mode with an IV that is the previous IV plus 1. In the indistinguishability game with chosen plaintexts, give an attacker that wins with probability 1, using one encryption after the challenge, and prove that it does. exercises/ex10_iv_game.py plays it.
Solution
Solution of Exercise 27.10.
The attacker picks and , one block each. The challenge is with . It predicts the next IV, , and asks for the encryption of , which is . It answers 0 if this equals , and 1 otherwise. If the two are equal. If , , and , so, being a permutation, they differ. The attacker is always right: probability 1, against for guessing. The program wins 200 games out of 200. The proof uses only the predictability of the IV, which is why CBC requires an unpredictable one.
Exercise 27.11 ★★★
Explain, from the structure of HMAC with a Merkle–Damgård hash, why knowing does not let an attacker compute by length extension. Which part of the computation would the attacker need, and why is it hidden?
Solution
Solution of Exercise 27.11.
with and the inner digest , . Extending the tag continues the outer chain: it gives , the outer hash of something longer than a key block and one digest. No HMAC computation ever hashes that, so this value is no tag. A tag for is with . The attacker could compute by extending , but is never published: it only enters the outer hash, and finding it from the tag means inverting behind the unknown key block . And even with in hand, the attacker would need to hash it. Length extension works on because its output is the whole internal state; HMAC hides that state behind a second, keyed hash.
Exercise 27.12 ★★★
Implement Poly1305 from RFC 8439, section 2.5: clamp , then for each 16-byte block, with a byte 01 appended, add it to the accumulator and multiply by modulo ; add . Pass the test vector of section 2.5.2. Why must a Poly1305 key never authenticate two messages?
Solution
Solution of Exercise 27.12.
exercises/ex12_poly1305.py: is the first 16 bytes read little-endian and clamped as section 2.5 prescribes, which clears the top four bits of four of its bytes and the bottom two bits of three others, the last 16. Each block, at most 16 bytes, is read little-endian with a byte 01 appended; ; the tag is . It gives a8061dc1305136c6c22b8baf0c0127a9 on the vector of section 2.5.2. With two messages under one key, , up to the reduction modulo : an attacker who sees both tags gets a polynomial equation in , with few roots, recovers and then , and forges any tag. That is why the AEAD derives a fresh Poly1305 key from the first keystream block of every nonce.
27.7 Weekend problem
Problem 27.1
Weekend problem — Collisions in the library’s short checksums
The library labels each catalogue record with a 32-bit checksum, the first 4 bytes of the record’s SHA-256, and uses it to find duplicates: two records with the same checksum are assumed to be the same. The program below hashes records until two checksums collide, in 200 runs.
def first_collision(run):
seen, i = {}, 0
while True:
record = f"run {run} record {i}".encode()
h = hashlib.sha256(record).digest()[:4]
if h in seen:
return i + 1, seen[h], record
seen[h] = record
i += 1
$ python birthday.py
run 0: 'run 0 record 52355' and 'run 0 record 53449' share 3ae0cfc8
first ten runs, hashes until a collision: 53450 48502 151348 61812 89680 74336 42301 22299 54582 80011
fewest 1,524, most 205,266
mean of 200 runs 78,631; sqrt(pi/2 * 2^32) = 82,137
ratio 0.957
Part I — The birthday bound.
- How many different checksums are there?
- Write the probability that records all have different checksums, assuming checksums uniform and independent.
- Bound it with Theorem 27.8 for and .
- For which is a collision more likely than not?
- Why is the bound about and not ?
- Is SHA-256 truncated to 32 bits still collision resistant? Preimage resistant?
Part II — Expected tries.
- What mean does give for ?
- Explain why the runs vary so much, from 1,524 to 205,266.
- Two hundred runs average 78,631. How far is that from the formula, in per cent?
- With 20 runs instead of 200, how much larger would the typical error of the mean be?
- The library has 60,000 records. What is the chance that two share a checksum?
- What happens in the library’s catalogue when they do?
Part III — Measured collisions.
- Check from Output 27.9 that run 0’s two records do share a checksum, and say how a reader can check it.
- Why are the records numbered with the run number in them?
- Would collisions come sooner if the records were short, or if they were long?
- The program keeps every checksum seen in a dictionary. How much memory does a run of 100,000 records take, roughly, and how could a collision be found with almost none?
- If an attacker can choose records, how does that change the risk?
- Could the library detect a duplicate safely with these checksums, and how?
Part IV — How many bits.
- For records and a -bit checksum, give the collision probability approximately.
- How many bits make it at most one in a million?
- What is it with 64 bits?
- Why is 128 bits the usual recommendation, rather than the minimum of question 20?
- What would SHA-256 in full cost the library in storage for records, against 4 bytes?
- Sum up: when does the first collision come for 32 bits, how close was the measurement, and how many bits does a catalogue of records need?
Solution
Solution of Problem 27.1.
1. .
2. .
3. At most : 0.988 for , so a collision with probability at least 1.2 %; 0.312 for , a collision with probability at least 69 %.
4. From records.
5. The danger is in pairs, not records: records make pairs, each colliding with probability , and the expected number of colliding pairs reaches 1 near .
6. Not collision resistant: 77,000 hashes, a fraction of a second, find a collision. Not preimage resistant either, against a determined attacker: about billion tries find a record with a given checksum, within reach of one computer.
7. .
8. The time to the first collision is a random variable with a wide distribution: its standard deviation is about , half its mean. The fewest and the most hashes in the 200 runs, 1,524 and 205,266, are both possible outcomes of one distribution.
9. is below .
10. The standard error of a mean shrinks as : about for 200 runs, so the measured gap of 3,500 is about one standard error. With 20 runs it would be times larger, about 9,600.
11. About for .
12. Two different records are taken for the same: one is merged into the other or dropped, and a book disappears from the catalogue without any error.
13. The two records run 0 record 52355 and run 0 record 53449 both start with the bytes 3ae0cfc8; anyone can check with hashlib.sha256(record).digest()[:4], and a test does.
14. So that every run hashes different records: without it all runs would find the same collision, and the 200 runs would be one run repeated.
15. Neither: SHA-256 spreads short and long inputs alike over its outputs, and only the number of records counts.
16. A dictionary of 100,000 entries, each with a 4-byte key and a record of about 20 bytes, takes some megabytes in Python. A cycle-finding method needs almost no memory: iterate from a start value; the sequence enters a cycle after about steps, and where it enters, two different inputs have the same checksum.
17. The bound assumes records independent of the checksum. An attacker who chooses records finds a collision in a fraction of a second, and can even make a new record collide with an existing one, with about tries, so as to have it removed as a duplicate.
18. Use the checksum as a filter only: when two checksums agree, compare the full records, or full SHA-256 digests, before deciding that they are duplicates.
19. About , as long as it is small.
20. gives : 79 bits.
21. : a 2.7 % chance of a collision in the catalogue.
22. With 128 bits the chance is about , the catalogue can grow a million-fold without concern, and an attacker needs about work for a collision; 79 bits would give an attacker , which is easy.
23. 32 bytes per record: 32 GB for records, against 4 GB for 32 bits; 128 bits, 16 GB, is the usual compromise.
24. With 32-bit checksums the first collision comes after records on average; 200 seeded runs averaged 78,631, within 5 %. A catalogue of records needs at least 79 bits for a one-in-a-million chance of any collision, 64 bits give 2.7 %, and 128 bits are the recommended size.
এই অধ্যায়ে সংজ্ঞায়িত পরিভাষা-শব্দ
- Block cipher, round key, AES
- Cryptographic hash function, preimage resistance, second-preimage resistance, collision resistance
- Kerckhoffs’s principle, attack model, perfect secrecy, computational security, indistinguishability
- Merkle–Damgård construction, length-extension attack
- Message authentication code, HMAC, authenticated encryption, AEAD
- Mode of operation, ECB, CBC, initialisation vector, padding, CTR, padding oracle
- One-time pad
- Stream cipher, keystream, nonce