TExcelTAD
Home › Number Theory & Cryptography › The Birthday Bound

The Birthday Bound

In a room of 23 people, two share a birthday with probability over 50 %. The same mathematics says that among about 2n/22^{n/2} random nn-bit values, two will collide. It sets the output size of hash functions, the safe amount of data per AES key, the size of random identifiers and nonces, and the speed of Pollard's rho.

The probability

Drawing kk values uniformly from NN possibilities, the probability that all are distinct is

P(no collision)=∏i=0k−1(1−iN)≈e−k(k−1)/(2N)P(\text{no collision}) = \prod_{i=0}^{k-1}\left(1 - \frac{i}{N}\right) \approx e^{-k(k-1)/(2N)}

using 1−x≈e−x1 - x \approx e^{-x}. A collision becomes likely (probability 1/2) at k≈2Nln⁡2≈1.18Nk \approx \sqrt{2N \ln 2} \approx 1.18\sqrt{N}, and the expected number of draws until the first collision is πN/2≈1.25N\sqrt{\pi N / 2} \approx 1.25\sqrt{N}.

python · try it yourself
import math

def p_collision(k, N):
    p = 1.0
    for i in range(k):
        p *= 1 - i / N
    return 1 - p

for k in (10, 23, 30, 50, 70):
    exact = p_collision(k, 365)
    approx = 1 - math.exp(-k * (k - 1) / (2 * 365))
    print(f"k={k:2}  exact {exact:.4f}  approx {approx:.4f}")
print("50% point for N = 365:", math.sqrt(2 * 365 * math.log(2)))
k=10  exact 0.1169  approx 0.1160
k=23  exact 0.5073  approx 0.5000
k=30  exact 0.7063  approx 0.6963
k=50  exact 0.9704  approx 0.9651
k=70  exact 0.9992  approx 0.9987
50% point for N = 365: 22.49438689559598

A collision in a truncated hash

Keep only the first 24 bits of SHA-256. Brute-forcing a preimage would take about 224≈16.72^{24} \approx 16.7 million tries; a collision appears after a few thousand:

python · try it yourself
import hashlib, math

seen = {}
i = 0
while True:
    h = hashlib.sha256(b"note %d" % i).digest()[:3]      # 24-bit truncated hash
    if h in seen:
        break
    seen[h] = i
    i += 1
print(f"collision after {i + 1} hashes: inputs {seen[h]} and {i}, digest {h.hex()}")
print("expected about", round(math.sqrt(math.pi / 2 * 2**24)))
collision after 4203 hashes: inputs 1076 and 4202, digest 5a34b2
expected about 5134

That is why an nn-bit hash only gives n/2n/2 bits of collision resistance, and why SHA-256 (not SHA-128) is used for 128-bit security.

Memory-free collision search

Storing every hash is not necessary. Treat f(x)=H(x)f(x) = H(x) truncated as a function on a finite set and iterate it: x,f(x),f(f(x)),…x, f(x), f(f(x)), \ldots must eventually cycle, and the entrance of the cycle is a collision. Floyd's tortoise-and-hare (as in Pollard's rho) finds it with constant memory.

python · try it yourself
import hashlib

def f(x):                                      # 24-bit values -> 24-bit values
    return hashlib.sha256(x.to_bytes(3, "big")).digest()[:3]

def g(x):
    return int.from_bytes(f(x), "big")

x0 = 12345
tort, hare = g(x0), g(g(x0))
while tort != hare:                            # find a meeting point on the cycle
    tort, hare = g(tort), g(g(hare))
tort = x0                                      # walk to the cycle entrance
while g(tort) != g(hare):
    tort, hare = g(tort), g(hare)
print("colliding inputs:", tort, hare, " same output:", f(tort).hex(), f(hare).hex(), tort != hare)
colliding inputs: 9041286 4716676  same output: bd24bf bd24bf True

(If the start already lies on the cycle the method returns two equal values; real implementations then restart.) Parallel versions with distinguished points found the MD5 and SHA-1 collisions.

Other places the bound appears

  • Block ciphers: with a 128-bit block, collisions among ciphertext blocks become likely after about 2642^{64} blocks, so modes like CBC and GCM limit data per key well below that (the "Sweet32" attack exploited 64-bit blocks in 3DES at 2322^{32} blocks).
  • Random nonces: AES-GCM with random 96-bit nonces must stay far below 2482^{48} messages per key; NIST caps it at 2322^{32}.
  • UUIDs: version 4 UUIDs have 122 random bits, so collisions need about 2612^{61} ids.
  • Hash tables: with kk keys in NN buckets, collisions start around N\sqrt{N} keys, long before the table is full.
python · try it yourself
import math

def items_for(prob, bits):
    N = 2.0**bits
    return math.sqrt(2 * N * math.log(1 / (1 - prob)))

for bits, what in ((64, "64-bit ids"), (96, "GCM 96-bit nonces"), (122, "UUIDv4"), (128, "128-bit hash")):
    print(f"{what:18} 1e-9 collision chance after about 2^{math.log2(items_for(1e-9, bits)):.1f} items")
64-bit ids         1e-9 collision chance after about 2^17.6 items
GCM 96-bit nonces  1e-9 collision chance after about 2^33.6 items
UUIDv4             1e-9 collision chance after about 2^46.6 items
128-bit hash       1e-9 collision chance after about 2^49.6 items

In software

  • Choose identifier sizes with the birthday bound: 64-bit random ids collide after about 4 billion items, which large systems do reach.
  • secrets.token_bytes(16) (128 bits) is a common choice for unique tokens.

Exercises

Exercise 1: The 50 % point

For a 32-bit hash, roughly how many inputs give a 50 % chance of a collision?

Answer

About 77000.

Solution

1.18232=1.18⋅65536≈77 0001.18\sqrt{2^{32}} = 1.18 \cdot 65536 \approx 77\,000. 32-bit checksums (CRC-32) therefore cannot be used to deduplicate large collections.

Exercise 2: Security level

What hash output length do you need for 128-bit collision resistance? For 128-bit preimage resistance?

Answer

256 bits; 128 bits.

Solution

Collisions cost 2n/22^{n/2}, so n=256n = 256. Preimages cost 2n2^n, so n=128n = 128 would suffice for that property alone.

Exercise 3: Simulate birthdays (code)

Using a seeded generator, simulate 10000 rooms of 23 people and estimate the probability of a shared birthday.

Answer

About 0.5 (the exact value is 0.507; this seeded run of 10000 rooms gives 0.499).

Solution
python · try it yourself
import numpy as np
rng = np.random.default_rng(23)
rooms = rng.integers(0, 365, size=(10000, 23))
shared = np.mean([len(set(r)) < 23 for r in rooms.tolist()])
print(round(float(shared), 3))
0.499

Test yourself

Among random nn-bit values, a collision is expected after about…

  1. 2n2^n values
  2. 2n/22^{n/2} values
  3. nn values
  4. n2n^2 values

How many people are needed for a better-than-even chance of a shared birthday?

  1. 183
  2. 50
  3. 23
  4. 366

Why does a 128-bit block cipher limit the data encrypted under one key?

  1. keys wear out
  2. block collisions become likely near 2642^{64} blocks
  3. AES is slow
  4. padding grows