---
title: "Symmetric Cryptography and Hash Functions"
book: "University Computer Science — Year 3"
subject: computer-science
language: en
chapter: 27
exercises: 12
source: https://one-course.com/books/computer-science/5/en/chapter/27-symmetric-cryptography-and-hash-functions
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 27 — Symmetric 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](#def-b3-symmetric-cryptography-security) 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](#def-b3-symmetric-cryptography-block) [AES](#def-b3-symmetric-cryptography-block) and the ways to chain it, the [stream cipher](#def-b3-symmetric-cryptography-stream) ChaCha20, the hash function SHA-256, and the [message authentication codes](#def-b3-symmetric-cryptography-mac) 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](#def-b3-symmetric-cryptography-modes) 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, $\oplus$, adds bits modulo 2, so $a \oplus b \oplus b = a$. In the mathematics books, the bytes form the finite field $\mathrm{GF}(2^8)$, polynomials over $\{0, 1\}$ 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: $P(C = c \mid M = m) = P(C = c \mid M = m')$ for all $m$, $m'$, $c$. 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 $m_0$, $m_1$ 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 $1/2$.

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 $n$-byte message $m$ with a uniformly random $n$-byte key $k$, used for one message only: $c = m \oplus k$, and $m = c \oplus k$.

**Theorem 27.3 (Shannon’s secrecy theorem).**

The [one-time pad](#def-b3-symmetric-cryptography-otp) has [perfect secrecy](#def-b3-symmetric-cryptography-security). Conversely, a cipher with [perfect secrecy](#def-b3-symmetric-cryptography-security) has at least as many keys as messages.

**Proof.** For the pad, given $m$ and $c$, exactly one key gives $c$, namely $k = m \oplus c$, so $P(C = c \mid M = m) = 2^{-8n}$, the same for every $m$. Conversely, take a ciphertext $c$ that occurs, from some message $m_0$ and some key. By [perfect secrecy](#def-b3-symmetric-cryptography-security), $P(C = c \mid M = m) = P(C = c \mid M = m_0) > 0$ for every message $m$, so for each $m$ some key encrypts $m$ to $c$. Decryption with a key is a function of $c$, so one key cannot decrypt $c$ 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 $c_1 = m_1 \oplus k$ and $c_2 = m_2 \oplus k$, then $c_1 \oplus c_2 = m_1 \oplus m_2$, the key is gone, and a guessed word in one message reveals the other at the same place.

```python
"""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}"
            )
```

***Listing 27.1.** A [one-time pad](#def-b3-symmetric-cryptography-otp), a key that turns the same ciphertext into any other message of the same length, and a key used twice. code/bachelor-3/27-symmetric-cryptography/listings/otp.py*

```
$ 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'
```

***Output 27.1.** Guessing “THE ” at position 0 gives MEET, which reads like text: a hit, THE starts one message and MEET the other. LIBRARY at 12 gives 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](#def-b3-symmetric-cryptography-security) for [computational security](#def-b3-symmetric-cryptography-security): a 16-byte key that encrypts gigabytes, secure as long as no one can do much better than trying the $2^{128}$ 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 $n$-bit blocks, one for each key, $E_k$, with an inverse $D_k$ that is efficient to compute when $k$ 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](#def-b3-symmetric-cryptography-block) treats the block as a $4 \times 4$ array of bytes. Each round applies four steps: SubBytes replaces every byte by its inverse in $\mathrm{GF}(2^8)$ followed by a fixed affine map, the only non-linear step; ShiftRows rotates row $r$ by $r$ places; MixColumns multiplies every column by a fixed matrix over $\mathrm{GF}(2^8)$, so that each output byte depends on the whole column; AddRoundKey XORs the [round key](#def-b3-symmetric-cryptography-block). Two rounds of ShiftRows and MixColumns already make every byte of the state depend on every byte of the input.

![One round of AES. AES-128 adds round key k_0 first, then runs ten rounds with k_1 to k_10.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-symmetric-cryptography/fig-4e500fb1ed2a.svg)

*One round of [AES](#def-b3-symmetric-cryptography-block). AES-128 adds [round key](#def-b3-symmetric-cryptography-block) $k_0$ first, then runs ten rounds with $k_1$ to $k_{10}$.*

```python
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)
```

***Listing 27.2.** AES-128 encryption: the initial key addition, nine full rounds, and a last round without MixColumns. code/bachelor-3/27-symmetric-cryptography/listings/aes.py*

```
$ 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
```

***Output 27.2.** The cipher example of FIPS 197: the S-box, two [round keys](#def-b3-symmetric-cryptography-block) and the ciphertext agree with the standard, and decryption gives the plaintext back.*

A [block cipher](#def-b3-symmetric-cryptography-block) 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 $P_1, \ldots, P_n$ with a [block cipher](#def-b3-symmetric-cryptography-block). *ECB mode* encrypts each block alone: $C_i = E_k(P_i)$. *CBC mode* chains them: $C_i = E_k(P_i \oplus C_{i-1})$, starting from $C_0$, an *initialisation vector* (IV) that must be unpredictable and is sent with the ciphertext; decryption computes $P_i = D_k(C_i) \oplus C_{i-1}$. *Padding* extends the message to a whole number of blocks; PKCS#7 padding adds $p$ bytes of value $p$, $1 \le p \le 16$, and is checked and removed after decryption. *CTR mode* turns the [block cipher](#def-b3-symmetric-cryptography-block) into a [stream cipher](#def-b3-symmetric-cryptography-stream): $C_i = P_i \oplus E_k(\mathit{ctr} + i)$, 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
```

***Output 27.3.** The picture has 384 blocks, only 41 of them different: ECB keeps exactly 41, CBC gives 384 different blocks.*

![A picture of 96 × 64 one-byte pixels, drawn from 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.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-symmetric-cryptography/fig-44b486731e23.svg)

![A picture of 96 × 64 one-byte pixels, drawn from 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.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-symmetric-cryptography/fig-b72835878d72.svg)

![A picture of 96 × 64 one-byte pixels, drawn from 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.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-symmetric-cryptography/fig-7c8f1961e22c.svg)

*A picture of $96 \times 64$ one-byte pixels, drawn from `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.*

```python
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)
```

***Listing 27.3.** CBC encryption: each block is XORed with the previous ciphertext block, the first with the IV, before it is encrypted. code/bachelor-3/27-symmetric-cryptography/listings/modes.py*

![Two modes. In CBC each ciphertext block feeds the next encryption, so equal plaintext blocks encrypt differently, and encryption is sequential. In CTR the cipher only produces a keystream from the counter, and the blocks can be computed in parallel; a repeated counter repeats the keystream.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-symmetric-cryptography/fig-6a74cc39b7f7.svg)

*Two modes. In CBC each ciphertext block feeds the next encryption, so equal plaintext blocks encrypt differently, and encryption is sequential. In CTR the cipher only produces a [keystream](#def-b3-symmetric-cryptography-stream) from the counter, and the blocks can be computed in parallel; a repeated counter repeats the [keystream](#def-b3-symmetric-cryptography-stream).*

CBC hides patterns but not errors. The receiver decrypts, then checks the [padding](#def-b3-symmetric-cryptography-modes), and a service that answers differently to bad [padding](#def-b3-symmetric-cryptography-modes) than to other errors gives the attacker one bit per query: is the last byte of $D_k(C) \oplus C'$ a valid [padding](#def-b3-symmetric-cryptography-modes), for a forged block $C'$ of the attacker’s choice? Vaudenay described in 2002 how this bit decrypts the whole message. The attacker changes the last byte of $C'$ until the [padding](#def-b3-symmetric-cryptography-modes) is valid: then the last byte of $D_k(C) \oplus C'$ is `01`, which gives the last byte of $D_k(C)$, 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.

```python
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))
```

***Listing 27.4.** One block of the attack: find $D_k(C)$ byte by byte from the end, forging the block before it so that the known bytes decrypt to the [padding](#def-b3-symmetric-cryptography-modes) sought. code/bachelor-3/27-symmetric-cryptography/listings/padding_oracle.py*

```
$ 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
```

***Output 27.4.** Three blocks recovered in 6,389 queries, without the key. When the service checks an [HMAC](#def-b3-symmetric-cryptography-mac) over the ciphertext before decrypting, the same 12,288 forged queries are all refused and reveal nothing.*

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](#def-b3-symmetric-cryptography-otp) 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](#def-b3-symmetric-cryptography-stream) is a reused pad, with the leak of [Output 27.1](#out-b3-symmetric-cryptography-otp). ChaCha20, designed by Bernstein and specified in RFC 8439, makes 64 bytes of [keystream](#def-b3-symmetric-cryptography-stream) from a 32-byte key, a 32-bit block counter and a 12-byte [nonce](#def-b3-symmetric-cryptography-stream). Its state is sixteen 32-bit words: four constants, the key, the counter and the [nonce](#def-b3-symmetric-cryptography-stream). 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.

```python
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)))
```

***Listing 27.5.** The quarter round, and the block function: ten double rounds, four on the columns of the $4 \times 4$ state and four on its diagonals. code/bachelor-3/27-symmetric-cryptography/listings/chacha20.py*

```
$ python chacha20.py
block 2.3.2: 10f1e7e4d13b5915500fdd1fa32071c4 ... True
cipher 2.4.2: 6e2e359a2568f98041ba0728dd0d6981 ... True
```

***Output 27.5.** The two test vectors of RFC 8439, sections 2.3.2 and 2.4.2, reproduced.*

ChaCha20 uses only additions, XORs and rotations of words, which take the same time whatever their values; table look-ups such as [AES](#def-b3-symmetric-cryptography-block)’s S-box can take a time that depends on the key through the cache, and RFC 8439 notes that many [AES](#def-b3-symmetric-cryptography-block) 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 $h$, finding any $m$ with $H(m) = h$ is infeasible; *second-preimage resistance* if, given $m$, finding $m' \ne m$ with $H(m') = H(m)$ 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 $q$ values independently and uniformly from a set of $N$. The probability that all are different is at most $e^{-q(q-1)/(2N)}$. So $q \approx \sqrt{2N \ln 2} \approx 1.18\sqrt{N}$ draws give a collision with probability at least $1/2$.

**Proof.** Facts used: $1 - x \le e^{-x}$ for every real $x$. The $i$-th draw, $i = 1, \ldots, q$, avoids the $i - 1$ earlier values, all different, with probability $1 - (i - 1)/N$, so

$$
P(\text{all different}) = \prod_{i=1}^{q} \Bigl(1 - \frac{i - 1}{N}\Bigr) \le \prod_{i=1}^{q} e^{-(i-1)/N} = e^{-q(q - 1)/(2N)}.
$$

This is at most $1/2$ as soon as $q(q - 1) \ge 2N \ln 2$, which holds for $q = \lceil \sqrt{2N \ln 2}\, \rceil + 1$. ∎

A finer computation gives the mean number of draws until the first collision, about $\sqrt{\pi N / 2}$. A digest of $b$ bits therefore resists collisions for only about $2^{b/2}$ work: the 256 bits of SHA-256 give $2^{128}$. 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](#def-b3-symmetric-cryptography-modes) it to whole blocks, with its length in the last one, and running a compression function $f$ along the blocks: $h_0$ is a fixed initial value, $h_i = f(h_{i-1}, M_i)$, and the digest is $h_n$. A *length-extension attack* uses $H(m)$ and the length of $m$, without $m$, to compute $H(m \,\|\, \mathit{pad} \,\|\, m')$ for any $m'$, by continuing the chain from $h_n$.

SHA-256, from FIPS 180-4, is a [Merkle–Damgård construction](#def-b3-symmetric-cryptography-md) 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.

```python
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))]
```

***Listing 27.6.** The compression function of SHA-256: a message schedule of 64 words, then 64 rounds over eight working words, added to the previous state. code/bachelor-3/27-symmetric-cryptography/listings/sha256.py*

```
$ 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
```

***Output 27.6.** The constants agree with FIPS 180-4, and the digests with Python’s `hashlib` on 1,000 random messages. A message of 56 bytes needs a second block: its 8-byte length no longer fits.*

![The Merkle–Damgård chain of H(k \,\|\, m), and its continuation. The tag is the whole state after the last block, so anyone who knows it can hash further blocks; the result is the tag of k \,\|\, m \,\|\, pad \,\|\, m'.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-symmetric-cryptography/fig-c85fec7b6e20.svg)

*The Merkle–Damgård chain of $H(k \,\|\, m)$, and its continuation. The tag is the whole state after the last block, so anyone who knows it can hash further blocks; the result is the tag of $k \,\|\, m \,\|\, \mathit{pad} \,\|\, m'$.*

## 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 $H$ with blocks of $B$ bytes: $\mathrm{HMAC}(K, m) = H\bigl((K \oplus \mathit{opad}) \,\|\, H((K \oplus \mathit{ipad}) \,\|\, m)\bigr)$, where the key is padded with zeros to $B$ bytes and $\mathit{ipad}$, $\mathit{opad}$ are the bytes `0x36` and `0x5C` repeated $B$ 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 $H(k \,\|\, m)$ falls to length extension. A toy library service authorises loans with such tags:

```python
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)
```

***Listing 27.7.** Forging a tag for a longer order: continue SHA-256 from the published tag, after the [padding](#def-b3-symmetric-cryptography-modes) the service itself added. code/bachelor-3/27-symmetric-cryptography/listings/length_ext.py*

```
$ 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
```

***Output 27.7.** The forged order ends with `&days=365` and is accepted. A service that parses the last `days` field lends the book for a year. Against [HMAC](#def-b3-symmetric-cryptography-mac) the same continuation fails.*

[HMAC](#def-b3-symmetric-cryptography-mac) 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](#exo-b3-symmetric-cryptography-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](#def-b3-symmetric-cryptography-modes) disappears. RFC 8439 defines such a scheme: ChaCha20 encrypts, and Poly1305, a one-time authenticator keyed by the first [keystream](#def-b3-symmetric-cryptography-stream) block of the [nonce](#def-b3-symmetric-cryptography-stream), authenticates the associated data and the ciphertext.

```python
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)
```

***Listing 27.8.** ChaCha20-Poly1305: a fresh Poly1305 key per [nonce](#def-b3-symmetric-cryptography-stream), encrypt then authenticate, and verify before decrypting. code/bachelor-3/27-symmetric-cryptography/listings/aead.py*

```
$ 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
```

***Output 27.8.** The [AEAD](#def-b3-symmetric-cryptography-mac) test vector of RFC 8439, section 2.8.2, and a ciphertext with one bit flipped, refused.*

![An Enigma I, the military model, in the Museo della Scienza e della Tecnologia, Milan (photograph by Alessandro Nassiri, 2012, CC BY-SA 4.0). The machine was invented by the German engineer Arthur Scherbius at the end of the First World War; its rotors scramble the 26 letters anew at each key press.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-symmetric-cryptography/img-76fc530c41cc.jpg)

*An Enigma I, the military model, in the Museo della Scienza e della Tecnologia, Milan (photograph by Alessandro Nassiri, 2012, CC BY-SA 4.0). The machine was invented by the German engineer Arthur Scherbius at the end of the First World War; its rotors scramble the 26 letters anew at each key press.*

## 27.6 Exercises

**Exercise 27.1 ★.**

A [one-time pad](#def-b3-symmetric-cryptography-otp) 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 of Exercise 27.1.**

$1011\,0110 \oplus 0110\,1100 = 1101\,1010$. The key that decrypts this ciphertext to $0000\,1111$ is the XOR of the two: $1101\,1010 \oplus 0000\,1111 = 1101\,0101$. 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 $P_1 = P_3$. In which of ECB, CBC and CTR is $C_1 = C_3$? 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 of Exercise 27.2.**

Only in ECB: $C_1 = E_k(P_1) = E_k(P_3) = C_3$. In CBC the inputs $P_1 \oplus C_0$ and $P_3 \oplus C_2$ differ unless $C_0 = C_2$, which happens with probability $2^{-128}$; in CTR the [keystream](#def-b3-symmetric-cryptography-stream) blocks of counters $\mathit{ctr}$ and $\mathit{ctr} + 2$ differ, since $E_k$ 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](#thm-b3-symmetric-cryptography-birthday), for a collision to be more likely than not? About how many on average until the first? How long would a machine computing $10^9$ digests per second take?

**Solution of Exercise 27.3.**

With $N = 2^{64}$, [Theorem 27.8](#thm-b3-symmetric-cryptography-birthday) gives a collision with probability at least $1/2$ after $\sqrt{2N \ln 2} \approx 5.06 \times 10^9$ digests, and the mean is $\sqrt{\pi N / 2} \approx 5.38 \times 10^9$. At $10^9$ digests per second, about five seconds. A 64-bit digest offers no [collision resistance](#def-b3-symmetric-cryptography-hash) against a computer.

**Exercise 27.4 ★.**

Without running it, say what the line `c1 xor c2 = m1 xor m2` of [Output 27.1](#out-b3-symmetric-cryptography-otp) contains at the positions where $m_1$ and $m_2$ have the same letter, and at the positions where one has a space and the other a capital letter.

**Solution of Exercise 27.4.**

The line is $m_1 \oplus m_2$, 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](#def-b3-symmetric-cryptography-modes) from the counter block 0. Show what an eavesdropper learns from two messages, then fix it with an 8-byte [nonce](#def-b3-symmetric-cryptography-stream) 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 of Exercise 27.5.**

Two messages encrypted from counter 0 use the same [keystream](#def-b3-symmetric-cryptography-stream), so $c_1 \oplus c_2 = m_1 \oplus m_2$, as the first line of the program’s output shows, and the attack of [Output 27.1](#out-b3-symmetric-cryptography-otp) applies. The fix puts an 8-byte [nonce](#def-b3-symmetric-cryptography-stream) in the first half of the counter block and the block number in the second, and sends the [nonce](#def-b3-symmetric-cryptography-stream) in front of the ciphertext. Two different [nonces](#def-b3-symmetric-cryptography-stream) give counter blocks that never meet, so no [keystream](#def-b3-symmetric-cryptography-stream) block repeats. One key then encrypts up to $2^{64}$ messages, each of up to $2^{64}$ blocks, $2^{68}$ bytes, if the [nonce](#def-b3-symmetric-cryptography-stream) is a counter. A random [nonce](#def-b3-symmetric-cryptography-stream) collides after about $2^{32}$ messages by the [birthday bound](#thm-b3-symmetric-cryptography-birthday), so a counter, or a longer [nonce](#def-b3-symmetric-cryptography-stream), is the safer choice.

**Exercise 27.6 ★★.**

Write `cbc_decrypt_checked(key, iv, c)` from the definition of CBC and of PKCS#7 [padding](#def-b3-symmetric-cryptography-modes), using only `decrypt_block`. It must refuse an empty ciphertext, a length that is not a multiple of 16, and a bad [padding](#def-b3-symmetric-cryptography-modes). Test it on the vector F.2.1 of SP 800-38A.

**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 $P_i = D_k(C_i) \oplus C_{i-1}$ with $C_0$ the IV; read $n$ from the last byte, and refuse unless $1 \le n \le 16$ and the last $n$ bytes all equal $n$. The test encrypts the four plaintext blocks of SP 800-38A F.2.1 followed by a full [padding](#def-b3-symmetric-cryptography-modes) 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](#def-b3-symmetric-cryptography-modes) 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](#def-b3-symmetric-cryptography-modes).

**Exercise 27.7 ★★.**

A letter-level [one-time pad](#def-b3-symmetric-cryptography-otp) shifts each letter of the message by a key letter, modulo 26. Prove that it has [perfect secrecy](#def-b3-symmetric-cryptography-security) when the key letters are independent and uniform. Then prove that the Vigenère cipher, which repeats a key of length $\ell$, does not, for messages longer than $\ell$.

**Solution of Exercise 27.7.**

Facts used: for fixed $m$ and $c$ in $\mathbb{Z}_{26}$, exactly one $k$ satisfies $c = m + k \bmod 26$. For a message of $n$ letters and independent uniform key letters, a ciphertext $c$ arises from $m$ only with the key $k_i = c_i - m_i \bmod 26$, of probability $26^{-n}$, the same for every $m$: [perfect secrecy](#def-b3-symmetric-cryptography-security). For Vigenère with a key of length $\ell$, take messages of length $\ell + 1$: letters 1 and $\ell + 1$ use the same key letter, so $c_1 - c_{\ell+1} = m_1 - m_{\ell+1} \bmod 26$. For $m = \mathrm{A}\ldots\mathrm{A}$, every ciphertext has $c_1 = c_{\ell+1}$; for $m = \mathrm{A}\ldots\mathrm{AB}$, none does. So $P(C = c \mid M = m)$ depends on $m$. The converse of [Theorem 27.3](#thm-b3-symmetric-cryptography-shannon) gives the same answer by counting: $26^\ell$ keys against $26^{\ell+1}$ messages. A test enumerates both cases for $\ell = 1$.

**Exercise 27.8 ★★.**

Prove that $q$ uniform draws from $N$ values collide with probability at most $q(q - 1)/(2N)$. Together with [Theorem 27.8](#thm-b3-symmetric-cryptography-birthday), what do the two bounds say about $q = \sqrt{N}$?

**Solution of Exercise 27.8.**

Facts used: $P(A \cup B) \le P(A) + P(B)$. A collision means $x_i = x_j$ for some pair $i < j$. Each of the $q(q - 1)/2$ pairs collides with probability $1/N$, so $P(\text{collision}) \le q(q - 1)/(2N)$. For $q = \sqrt{N}$ this upper bound is about $1/2$, and the theorem’s lower bound $1 - e^{-q(q-1)/(2N)}$ is about $1 - e^{-1/2} \approx 0.39$. So $\sqrt{N}$ draws collide with probability between 0.39 and 0.5: the collision threshold is $\sqrt{N}$, up to a constant factor. A test checks the upper bound by simulation for $N = 1000$, $q = 30$.

**Exercise 27.9 ★★.**

With PKCS#7 [padding](#def-b3-symmetric-cryptography-modes) and 16-byte blocks, how many blocks and [padding](#def-b3-symmetric-cryptography-modes) 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](#def-b3-symmetric-cryptography-modes)?

**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](#def-b3-symmetric-cryptography-modes) bytes: always $16 - (\ell \bmod 16)$ 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](#def-b3-symmetric-cryptography-modes). [Padding](#def-b3-symmetric-cryptography-modes) must be removable without knowing the length, so every message gets at least one [padding](#def-b3-symmetric-cryptography-modes) byte, and one already a whole number of blocks gets a full block.

**Exercise 27.10 ★★★.**

A service encrypts in [CBC mode](#def-b3-symmetric-cryptography-modes) with an IV that is the previous IV plus 1. In the [indistinguishability](#def-b3-symmetric-cryptography-security) 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 of Exercise 27.10.**

The attacker picks $m_0 = 0^{16}$ and $m_1 = 1^{128}$, one block each. The challenge is $(\mathit{iv}_1, C^*)$ with $C^* = E_k(m_b \oplus \mathit{iv}_1)$. It predicts the next IV, $\mathit{iv}_2 = \mathit{iv}_1 + 1$, and asks for the encryption of $m' = m_0 \oplus \mathit{iv}_1 \oplus \mathit{iv}_2$, which is $E_k(m' \oplus \mathit{iv}_2) = E_k(m_0 \oplus \mathit{iv}_1)$. It answers 0 if this equals $C^*$, and 1 otherwise. If $b = 0$ the two are equal. If $b = 1$, $C^* = E_k(m_1 \oplus \mathit{iv}_1)$, and $m_1 \oplus \mathit{iv}_1 \ne m_0 \oplus \mathit{iv}_1$, so, $E_k$ being a permutation, they differ. The attacker is always right: probability 1, against $1/2$ 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](#def-b3-symmetric-cryptography-mac) with a Merkle–Damgård hash, why knowing $\mathrm{HMAC}(K, m)$ does not let an attacker compute $\mathrm{HMAC}(K, m \,\|\, \mathit{pad} \,\|\, m')$ by length extension. Which part of the computation would the attacker need, and why is it hidden?

**Solution of Exercise 27.11.**

$\mathrm{HMAC}(K, m) = H(K_o \,\|\, d)$ with $K_o = K \oplus \mathit{opad}$ and the inner digest $d = H(K_i \,\|\, m)$, $K_i = K \oplus \mathit{ipad}$. Extending the tag continues the outer chain: it gives $H(K_o \,\|\, d \,\|\, \mathit{pad} \,\|\, m')$, the outer hash of something longer than a key block and one digest. No [HMAC](#def-b3-symmetric-cryptography-mac) computation ever hashes that, so this value is no tag. A tag for $m \,\|\, \mathit{pad} \,\|\, m'$ is $H(K_o \,\|\, d')$ with $d' = H(K_i \,\|\, m \,\|\, \mathit{pad} \,\|\, m')$. The attacker could compute $d'$ by extending $d$, but $d$ is never published: it only enters the outer hash, and finding it from the tag means inverting $H$ behind the unknown key block $K_o$. And even with $d'$ in hand, the attacker would need $K_o$ to hash it. Length extension works on $H(k \,\|\, m)$ because its output is the whole internal state; [HMAC](#def-b3-symmetric-cryptography-mac) hides that state behind a second, keyed hash.

**Exercise 27.12 ★★★.**

Implement Poly1305 from RFC 8439, section 2.5: clamp $r$, then for each 16-byte block, with a byte `01` appended, add it to the accumulator and multiply by $r$ modulo $2^{130} - 5$; add $s$. Pass the test vector of section 2.5.2. Why must a Poly1305 key never authenticate two messages?

**Solution of Exercise 27.12.**

`exercises/ex12_poly1305.py`: $r$ 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, $s$ the last 16. Each block, at most 16 bytes, is read little-endian with a byte `01` appended; $a \leftarrow (a + n) \cdot r \bmod (2^{130} - 5)$; the tag is $(a + s) \bmod 2^{128}$. It gives `a8061dc1305136c6c22b8baf0c0127a9` on the vector of section 2.5.2. With two messages under one key, $t_1 - t_2 \equiv P_1(r) - P_2(r)$, up to the reduction modulo $2^{128}$: an attacker who sees both tags gets a polynomial equation in $r$, with few roots, recovers $r$ and then $s$, and forges any tag. That is why the [AEAD](#def-b3-symmetric-cryptography-mac) derives a fresh Poly1305 key from the first [keystream](#def-b3-symmetric-cryptography-stream) block of every [nonce](#def-b3-symmetric-cryptography-stream).

## 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.

```python

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
```

***Listing 27.9.** Hash numbered records until a checksum repeats. code/bachelor-3/27-symmetric-cryptography/listings/birthday.py*

```
$ 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
```

***Output 27.9.** Two hundred runs: the first collision comes after 78,631 records on average, within 5 % of $\sqrt{\pi/2 \cdot 2^{32}}$.*

**Part I — The birthday bound.**

1. How many different checksums are there?
2. Write the probability that $q$ records all have different checksums, assuming checksums uniform and independent.
3. Bound it with [Theorem 27.8](#thm-b3-symmetric-cryptography-birthday) for $q = 10{,}000$ and $q = 100{,}000$ .
4. For which $q$ is a collision more likely than not?
5. Why is the bound about $\sqrt{N}$ and not $N$ ?
6. Is SHA-256 truncated to 32 bits still collision resistant? Preimage resistant?

**Part II — Expected tries.**

7. What mean does $\sqrt{\pi N / 2}$ give for $N = 2^{32}$ ?
8. Explain why the runs vary so much, from 1,524 to 205,266.
9. Two hundred runs average 78,631. How far is that from the formula, in per cent?
10. With 20 runs instead of 200, how much larger would the typical error of the mean be?
11. The library has 60,000 records. What is the chance that two share a checksum?
12. What happens in the library’s catalogue when they do?

**Part III — Measured collisions.**

13. Check from [Output 27.9](#out-b3-symmetric-cryptography-birthday) that run 0’s two records do share a checksum, and say how a reader can check it.
14. Why are the records numbered with the run number in them?
15. Would collisions come sooner if the records were short, or if they were long?
16. 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?
17. If an attacker can choose records, how does that change the risk?
18. Could the library detect a duplicate safely with these checksums, and how?

**Part IV — How many bits.**

19. For $10^9$ records and a $b$ -bit checksum, give the collision probability approximately.
20. How many bits make it at most one in a million?
21. What is it with 64 bits?
22. Why is 128 bits the usual recommendation, rather than the minimum of question 20?
23. What would SHA-256 in full cost the library in storage for $10^9$ records, against 4 bytes?
24. Sum up: when does the first collision come for 32 bits, how close was the measurement, and how many bits does a catalogue of $10^9$ records need?

**Solution of Problem 27.1.**

**1.** $N = 2^{32} = 4{,}294{,}967{,}296$.

**2.** $\prod_{i=1}^{q} \bigl(1 - (i - 1)/N\bigr)$.

**3.** At most $e^{-q(q-1)/(2N)}$: 0.988 for $q = 10{,}000$, so a collision with probability at least 1.2 %; 0.312 for $q = 100{,}000$, a collision with probability at least 69 %.

**4.** From $q \approx \sqrt{2N \ln 2} \approx 77{,}163$ records.

**5.** The danger is in pairs, not records: $q$ records make $q(q - 1)/2$ pairs, each colliding with probability $1/N$, and the expected number of colliding pairs reaches 1 near $q = \sqrt{2N}$.

**6.** Not collision resistant: 77,000 hashes, a fraction of a second, find a collision. Not preimage resistant either, against a determined attacker: about $2^{32} \approx 4.3$ billion tries find a record with a given checksum, within reach of one computer.

**7.** $\sqrt{\pi \cdot 2^{32} / 2} \approx 82{,}137$.

**8.** The time to the first collision is a random variable with a wide distribution: its standard deviation is about $\sqrt{(2 - \pi/2)N} \approx 42{,}900$, 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.** $78{,}631$ is $4.3\,\%$ below $82{,}137$.

**10.** The standard error of a mean shrinks as $1/\sqrt{n}$: about $42{,}900/\sqrt{200} \approx 3{,}000$ for 200 runs, so the measured gap of 3,500 is about one standard error. With 20 runs it would be $\sqrt{10} \approx 3.2$ times larger, about 9,600.

**11.** About $1 - e^{-q^2/(2N)} \approx 34\,\%$ for $q = 60{,}000$.

**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 $x \mapsto h(x)$ from a start value; the sequence enters a cycle after about $\sqrt{N}$ 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 $2^{32}$ 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 $q^2 / 2^{b+1} = 10^{18} / 2^{b+1}$, as long as it is small.

**20.** $10^{18} / 2^{b+1} \le 10^{-6}$ gives $b \ge \log_2(10^{18} / (2 \cdot 10^{-6})) \approx 78.7$: 79 bits.

**21.** $10^{18} / 2^{65} \approx 0.027$: a 2.7 % chance of a collision in the catalogue.

**22.** With 128 bits the chance is about $10^{-21}$, the catalogue can grow a million-fold without concern, and an attacker needs about $2^{64}$ work for a collision; 79 bits would give an attacker $2^{40}$, which is easy.

**23.** 32 bytes per record: 32 GB for $10^9$ 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 $\sqrt{\pi/2 \cdot 2^{32}} \approx 82{,}000$ records on average; 200 seeded runs averaged 78,631, within 5 %. A catalogue of $10^9$ 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.
