কম্পিউটার বিজ্ঞান · বই 5 · স্নাতক তৃতীয় বর্ষ

University Computer Science — Year 3

এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: 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, ⊕\oplus, adds bits modulo 2, so a⊕b⊕b=aa \oplus b \oplus b = a. In the mathematics books, the bytes form the finite field GF(28)\mathrm{GF}(2^8), polynomials over {0,1}\{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∣M=m)=P(C=c∣M=m′)P(C = c \mid M = m) = P(C = c \mid M = m') for all mm, m′m', cc. 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 m0m_0, m1m_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/21/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 nn-byte message mm with a uniformly random nn-byte key kk, used for one message only: c=m⊕kc = m \oplus k, and m=c⊕km = c \oplus k.

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 mm and cc, exactly one key gives cc, namely k=m⊕ck = m \oplus c, so P(C=c∣M=m)=2−8nP(C = c \mid M = m) = 2^{-8n}, the same for every mm. Conversely, take a ciphertext cc that occurs, from some message m0m_0 and some key. By perfect secrecy, P(C=c∣M=m)=P(C=c∣M=m0)>0P(C = c \mid M = m) = P(C = c \mid M = m_0) > 0 for every message mm, so for each mm some key encrypts mm to cc. Decryption with a key is a function of cc, so one key cannot decrypt cc 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 c1=m1⊕kc_1 = m_1 \oplus k and c2=m2⊕kc_2 = m_2 \oplus k, then c1⊕c2=m1⊕m2c_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.

"""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, 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 for computational security: a 16-byte key that encrypts gigabytes, secure as long as no one can do much better than trying the 21282^{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 nn-bit blocks, one for each key, EkE_k, with an inverse DkD_k that is efficient to compute when kk 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 4×44 \times 4 array of bytes. Each round applies four steps: SubBytes replaces every byte by its inverse in GF(28)\mathrm{GF}(2^8) followed by a fixed affine map, the only non-linear step; ShiftRows rotates row rr by rr places; MixColumns multiplies every column by a fixed matrix over GF(28)\mathrm{GF}(2^8), 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.

One round of AES. AES-128 adds round key k_0 first, then runs ten rounds with k_1 to k_10.
One round of AES. AES-128 adds round key k0k_0 first, then runs ten rounds with k1k_1 to k10k_{10}.
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 and the ciphertext agree with the standard, and decryption gives the plaintext back.

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 P1,…,PnP_1, \ldots, P_n with a block cipher. ECB mode encrypts each block alone: Ci=Ek(Pi)C_i = E_k(P_i). CBC mode chains them: Ci=Ek(Pi⊕Ci−1)C_i = E_k(P_i \oplus C_{i-1}), starting from C0C_0, an initialisation vector (IV) that must be unpredictable and is sent with the ciphertext; decryption computes Pi=Dk(Ci)⊕Ci−1P_i = D_k(C_i) \oplus C_{i-1}. Padding extends the message to a whole number of blocks; PKCS#7 padding adds pp bytes of value pp, 1≤p≤161 \le p \le 16, and is checked and removed after decryption. CTR mode turns the block cipher into a stream cipher: Ci=Pi⊕Ek(ctr+i)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. 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. 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.
A picture of 96×6496 \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.
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.
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.

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 Dk(C)⊕C′D_k(C) \oplus C' a valid padding, for a forged block C′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′C' until the padding is valid: then the last byte of Dk(C)⊕C′D_k(C) \oplus C' is 01, which gives the last byte of Dk(C)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.

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 Dk(C)D_k(C) byte by byte from the end, forging the block before it so that the known bytes decrypt to the padding 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 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 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)))
Listing 27.5. The quarter round, and the block function: ten double rounds, four on the columns of the 4×44 \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’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 hh, finding any mm with H(m)=hH(m) = h is infeasible; second-preimage resistance if, given mm, finding m′≠mm' \ne m with H(m′)=H(m)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 qq values independently and uniformly from a set of NN. The probability that all are different is at most e−q(q−1)/(2N)e^{-q(q-1)/(2N)}. So q≈2Nln⁡2≈1.18Nq \approx \sqrt{2N \ln 2} \approx 1.18\sqrt{N} draws give a collision with probability at least 1/21/2.

Proof. Facts used: 1−x≤e−x1 - x \le e^{-x} for every real xx. The ii-th draw, i=1,…,qi = 1, \ldots, q, avoids the i−1i - 1 earlier values, all different, with probability 1−(i−1)/N1 - (i - 1)/N, so

P(all different)=∏i=1q(1−i−1N)≤∏i=1qe−(i−1)/N=e−q(q−1)/(2N).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/21/2 as soon as q(q−1)≥2Nln⁡2q(q - 1) \ge 2N \ln 2, which holds for q=⌈2Nln⁡2 ⌉+1q = \lceil \sqrt{2N \ln 2}\, \rceil + 1. ∎

A finer computation gives the mean number of draws until the first collision, about πN/2\sqrt{\pi N / 2}. A digest of bb bits therefore resists collisions for only about 2b/22^{b/2} work: the 256 bits of SHA-256 give 21282^{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 it to whole blocks, with its length in the last one, and running a compression function ff along the blocks: h0h_0 is a fixed initial value, hi=f(hi−1,Mi)h_i = f(h_{i-1}, M_i), and the digest is hnh_n. A length-extension attack uses H(m)H(m) and the length of mm, without mm, to compute H(m ∥ pad ∥ m′)H(m \,\|\, \mathit{pad} \,\|\, m') for any m′m', by continuing the chain from hnh_n.

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))]
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'.
The Merkle–Damgård chain of H(k ∥ m)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′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 HH with blocks of BB bytes: HMAC(K,m)=H((K⊕opad) ∥ H((K⊕ipad) ∥ m))\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 BB bytes and ipad\mathit{ipad}, opad\mathit{opad} are the bytes 0x36 and 0x5C repeated BB 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)H(k \,\|\, m) 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)
Listing 27.7. Forging a tag for a longer order: continue SHA-256 from the published tag, after the padding 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 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)
Listing 27.8. ChaCha20-Poly1305: a fresh Poly1305 key per nonce, 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 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.
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 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.

1011 0110⊕0110 1100=1101 10101011\,0110 \oplus 0110\,1100 = 1101\,1010. The key that decrypts this ciphertext to 0000 11110000\,1111 is the XOR of the two: 1101 1010⊕0000 1111=1101 01011101\,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 P1=P3P_1 = P_3. In which of ECB, CBC and CTR is C1=C3C_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

Solution of Exercise 27.2.

Only in ECB: C1=Ek(P1)=Ek(P3)=C3C_1 = E_k(P_1) = E_k(P_3) = C_3. In CBC the inputs P1⊕C0P_1 \oplus C_0 and P3⊕C2P_3 \oplus C_2 differ unless C0=C2C_0 = C_2, which happens with probability 2−1282^{-128}; in CTR the keystream blocks of counters ctr\mathit{ctr} and ctr+2\mathit{ctr} + 2 differ, since EkE_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, for a collision to be more likely than not? About how many on average until the first? How long would a machine computing 10910^9 digests per second take?

Solution

Solution of Exercise 27.3.

With N=264N = 2^{64}, Theorem 27.8 gives a collision with probability at least 1/21/2 after 2Nln⁡2≈5.06×109\sqrt{2N \ln 2} \approx 5.06 \times 10^9 digests, and the mean is πN/2≈5.38×109\sqrt{\pi N / 2} \approx 5.38 \times 10^9. At 10910^9 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 m1m_1 and m2m_2 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 m1⊕m2m_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 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 c1⊕c2=m1⊕m2c_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 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 2642^{64} messages, each of up to 2642^{64} blocks, 2682^{68} bytes, if the nonce is a counter. A random nonce collides after about 2322^{32} 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 Pi=Dk(Ci)⊕Ci−1P_i = D_k(C_i) \oplus C_{i-1} with C0C_0 the IV; read nn from the last byte, and refuse unless 1≤n≤161 \le n \le 16 and the last nn bytes all equal nn. 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 ℓ\ell, does not, for messages longer than ℓ\ell.

Solution

Solution of Exercise 27.7.

Facts used: for fixed mm and cc in Z26\mathbb{Z}_{26}, exactly one kk satisfies c=m+k mod 26c = m + k \bmod 26. For a message of nn letters and independent uniform key letters, a ciphertext cc arises from mm only with the key ki=ci−mi mod 26k_i = c_i - m_i \bmod 26, of probability 26−n26^{-n}, the same for every mm: perfect secrecy. For Vigenère with a key of length ℓ\ell, take messages of length ℓ+1\ell + 1: letters 1 and ℓ+1\ell + 1 use the same key letter, so c1−cℓ+1=m1−mℓ+1 mod 26c_1 - c_{\ell+1} = m_1 - m_{\ell+1} \bmod 26. For m=A…Am = \mathrm{A}\ldots\mathrm{A}, every ciphertext has c1=cℓ+1c_1 = c_{\ell+1}; for m=A…ABm = \mathrm{A}\ldots\mathrm{AB}, none does. So P(C=c∣M=m)P(C = c \mid M = m) depends on mm. The converse of Theorem 27.3 gives the same answer by counting: 26ℓ26^\ell keys against 26ℓ+126^{\ell+1} messages. A test enumerates both cases for ℓ=1\ell = 1.

Exercise 27.8 ★★

Prove that qq uniform draws from NN values collide with probability at most q(q−1)/(2N)q(q - 1)/(2N). Together with Theorem 27.8, what do the two bounds say about q=Nq = \sqrt{N}?

Solution

Solution of Exercise 27.8.

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

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 16−(ℓ mod 16)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. 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 m0=016m_0 = 0^{16} and m1=1128m_1 = 1^{128}, one block each. The challenge is (iv1,C∗)(\mathit{iv}_1, C^*) with C∗=Ek(mb⊕iv1)C^* = E_k(m_b \oplus \mathit{iv}_1). It predicts the next IV, iv2=iv1+1\mathit{iv}_2 = \mathit{iv}_1 + 1, and asks for the encryption of m′=m0⊕iv1⊕iv2m' = m_0 \oplus \mathit{iv}_1 \oplus \mathit{iv}_2, which is Ek(m′⊕iv2)=Ek(m0⊕iv1)E_k(m' \oplus \mathit{iv}_2) = E_k(m_0 \oplus \mathit{iv}_1). It answers 0 if this equals C∗C^*, and 1 otherwise. If b=0b = 0 the two are equal. If b=1b = 1, C∗=Ek(m1⊕iv1)C^* = E_k(m_1 \oplus \mathit{iv}_1), and m1⊕iv1≠m0⊕iv1m_1 \oplus \mathit{iv}_1 \ne m_0 \oplus \mathit{iv}_1, so, EkE_k being a permutation, they differ. The attacker is always right: probability 1, against 1/21/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 with a Merkle–Damgård hash, why knowing HMAC(K,m)\mathrm{HMAC}(K, m) does not let an attacker compute HMAC(K,m ∥ pad ∥ m′)\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

Solution of Exercise 27.11.

HMAC(K,m)=H(Ko ∥ d)\mathrm{HMAC}(K, m) = H(K_o \,\|\, d) with Ko=K⊕opadK_o = K \oplus \mathit{opad} and the inner digest d=H(Ki ∥ m)d = H(K_i \,\|\, m), Ki=K⊕ipadK_i = K \oplus \mathit{ipad}. Extending the tag continues the outer chain: it gives H(Ko ∥ d ∥ pad ∥ m′)H(K_o \,\|\, d \,\|\, \mathit{pad} \,\|\, m'), 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 m ∥ pad ∥ m′m \,\|\, \mathit{pad} \,\|\, m' is H(Ko ∥ d′)H(K_o \,\|\, d') with d′=H(Ki ∥ m ∥ pad ∥ m′)d' = H(K_i \,\|\, m \,\|\, \mathit{pad} \,\|\, m'). The attacker could compute d′d' by extending dd, but dd is never published: it only enters the outer hash, and finding it from the tag means inverting HH behind the unknown key block KoK_o. And even with d′d' in hand, the attacker would need KoK_o to hash it. Length extension works on H(k ∥ m)H(k \,\|\, m) 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 rr, then for each 16-byte block, with a byte 01 appended, add it to the accumulator and multiply by rr modulo 2130−52^{130} - 5; add ss. 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: rr 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, ss the last 16. Each block, at most 16 bytes, is read little-endian with a byte 01 appended; a←(a+n)⋅r mod (2130−5)a \leftarrow (a + n) \cdot r \bmod (2^{130} - 5); the tag is (a+s) mod 2128(a + s) \bmod 2^{128}. It gives a8061dc1305136c6c22b8baf0c0127a9 on the vector of section 2.5.2. With two messages under one key, t1−t2≡P1(r)−P2(r)t_1 - t_2 \equiv P_1(r) - P_2(r), up to the reduction modulo 21282^{128}: an attacker who sees both tags gets a polynomial equation in rr, with few roots, recovers rr and then ss, 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
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 π/2⋅232\sqrt{\pi/2 \cdot 2^{32}}.

Part I — The birthday bound.

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

Part II — Expected tries.

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

Part III — Measured collisions.

  1. Check from Output 27.9 that run 0’s two records do share a checksum, and say how a reader can check it.
  2. Why are the records numbered with the run number in them?
  3. Would collisions come sooner if the records were short, or if they were long?
  4. 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?
  5. If an attacker can choose records, how does that change the risk?
  6. Could the library detect a duplicate safely with these checksums, and how?

Part IV — How many bits.

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

Solution of Problem 27.1.

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

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

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

4. From q≈2Nln⁡2≈77,163q \approx \sqrt{2N \ln 2} \approx 77{,}163 records.

5. The danger is in pairs, not records: qq records make q(q−1)/2q(q - 1)/2 pairs, each colliding with probability 1/N1/N, and the expected number of colliding pairs reaches 1 near q=2Nq = \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 232≈4.32^{32} \approx 4.3 billion tries find a record with a given checksum, within reach of one computer.

7. π⋅232/2≈82,137\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 (2−π/2)N≈42,900\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,63178{,}631 is 4.3 %4.3\,\% below 82,13782{,}137.

10. The standard error of a mean shrinks as 1/n1/\sqrt{n}: about 42,900/200≈3,00042{,}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 10≈3.2\sqrt{10} \approx 3.2 times larger, about 9,600.

11. About 1−e−q2/(2N)≈34 %1 - e^{-q^2/(2N)} \approx 34\,\% for q=60,000q = 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↦h(x)x \mapsto h(x) from a start value; the sequence enters a cycle after about N\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 2322^{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 q2/2b+1=1018/2b+1q^2 / 2^{b+1} = 10^{18} / 2^{b+1}, as long as it is small.

20. 1018/2b+1≤10−610^{18} / 2^{b+1} \le 10^{-6} gives b≥log⁡2(1018/(2⋅10−6))≈78.7b \ge \log_2(10^{18} / (2 \cdot 10^{-6})) \approx 78.7: 79 bits.

21. 1018/265≈0.02710^{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−2110^{-21}, the catalogue can grow a million-fold without concern, and an attacker needs about 2642^{64} work for a collision; 79 bits would give an attacker 2402^{40}, which is easy.

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

এই অধ্যায়ে সংজ্ঞায়িত পরিভাষা-শব্দ

পরিভাষায় সব 1050 টি শব্দ দেখো