Sub topic 9
How likely is a collision? The birthday bound
This chapter assumes you know that hash collisions are unavoidable (the pigeonhole principle). It also assumes you are comfortable with exponentials, math.exp, and Python sets. It answers a different question: how soon do collisions show up, and how does that depend on the number of output bits?
The surprise
Suppose a hash has 2^32 possible outputs, about 4.3 billion. You might expect to hash billions of items before two of them collide. In practice you need only about 77,000.
This is the birthday problem. In a room of 23 people, the chance that two share a birthday is about 50%, even though there are 365 possible birthdays. The reason is that you are not checking one pair. You are checking every pair, and the number of pairs grows with the square of the group size.
Counting pairs
With n items there are n(n-1)/2 distinct pairs. Each pair collides with probability 1/m, where m is the number of possible hash values and the hash is uniform. So the expected number of colliding pairs is:
expected collisions ≈ n(n-1) / (2m)For 23 people and m = 365, that gives 23·22/730 ≈ 0.69 expected matching pairs. This already hints at the 50% answer.
The probability formula
To get an actual probability, compute the chance that no collision occurs. Item 1 is always fine. Item 2 avoids item 1 with probability 1 - 1/m. Item 3 avoids both with probability 1 - 2/m, and so on:
P(no collision) = (1 - 1/m)(1 - 2/m)...(1 - (n-1)/m)For small x, 1 - x ≈ e^(-x). Applying that to every factor and summing the exponents gives:
P(no collision) ≈ exp(-n(n-1) / (2m))
P(collision) ≈ 1 - exp(-n(n-1) / (2m))This is the approximation used in the Topic Spine. It is accurate when n is much smaller than m. Near n ≈ m it stops being reliable, but by then a collision is almost certain.
Computing it in Python
import math
def collision_probability(n, bits):
m = 2 ** bits
x = n * (n - 1) / (2 * m)
return -math.expm1(-x) # same as 1 - exp(-x), but accurate for tiny x
print(collision_probability(77_000, 32)) # roughly one half
print(collision_probability(1_000_000, 64)) # about 2.7e-08The textbook form 1 - math.exp(-x) works for the first line. For very small x it loses digits to floating-point rounding, because exp(-x) is almost exactly 1. math.expm1 computes exp(x) - 1 without that loss, which matters for the 64-bit case.
The first line prints about 0.498. The second prints about 2.7e-08: a million items in a 64-bit space almost never collide.
The 50% rule of thumb
Setting the probability to 1/2 and solving for n gives:
n ≈ 1.1774 × sqrt(m) = 1.1774 × 2^(bits/2)So the number of items you need is about the square root of the output space. Each extra bit multiplies the safe item count by only about 1.41, not 2.
| Output bits | Items for ~50% collision chance |
|---|---|
| 16 | about 300 |
| 32 | about 77,000 |
| 64 | about 5.1 billion |
| 128 | about 2.2 × 10^19 |
| 256 | about 4.0 × 10^38 |
The curve is not a straight line. It starts slowly, rises fast around the square-root point, and then flattens toward 100%.
Checking the theory by simulation
You can verify the bound by shrinking a real hash to a few bits and counting how many random inputs it takes to see the first repeat.
import hashlib
import math
import random
def first_collision(bits):
seen = set()
count = 0
while True:
count += 1
data = random.getrandbits(64).to_bytes(8, "big")
digest = hashlib.sha256(data).digest()
value = int.from_bytes(digest, "big") >> (256 - bits) # keep top bits
if value in seen:
return count
seen.add(value)
bits = 16
trials = 300
average = sum(first_collision(bits) for _ in range(trials)) / trials
predicted = math.sqrt(math.pi * 2**bits / 2)
print(f"measured average: {average:.0f}")
print(f"predicted mean: {predicted:.0f}")The predicted mean for the first collision is sqrt(πm/2). For 16 bits that is about 321. The measured value varies from run to run, but it should land within a few percent of that. Raising bits to 24 still runs quickly and predicts about 5,100 items.
What the bound means in practice
Hash tables
Table collisions are expected, not failures. Hashing 1,000 keys into 1,000,000 buckets gives about 0.5 expected colliding pairs. The chance of at least one is about 39%. A hash table handles this with chaining or probing. The birthday bound explains why you cannot size a table large enough to avoid collisions: you would need roughly n² buckets.
Fingerprints and identifiers
Some systems use a hash as an identity: deduplication, content-addressed storage, cache keys. Here a collision means two different things are treated as the same, so you need the collision probability to be negligible. Choose the bits from the bound. A 32-bit fingerprint is unsafe past a few tens of thousands of items. A 64-bit fingerprint is comfortable for millions of items. For a store with billions of objects, use 128 bits or more.
Cryptographic strength
The birthday bound sets the ceiling on collision resistance. An n-bit hash can offer at most about 2^(n/2) work against collisions, because that is how long generic birthday search takes. That is why SHA-256 gives about 128 bits of collision security. A hash with 128 output bits gives only about 64 bits of collision security, which is within reach of a well-funded attacker.
Common errors
- Using the bound for a specific target. The chance that a new item collides with one particular existing item is only 1/m. The birthday effect needs the freedom to match any pair.
- Assuming a linear relationship. Doubling the items roughly quadruples the expected pairs. Adding one bit to the output does not double your safety margin in item count.
- Trusting the formula for non-uniform hashes. The calculation assumes every output is equally likely. A weak hash, such as summing character codes, collides far sooner than the bound predicts. The bound is a best case.
- Using the approximation when n is close to m. The
expshortcut is for n much smaller than m. In that regime the answer is close to 1 anyway. - Forgetting truncation. Keeping 32 bits of a SHA-256 digest gives a 32-bit collision profile, whatever the original hash offered.
Exercises
Exercise
A hash produces 40-bit values. Roughly how many random items must you hash before the chance of a collision reaches 50%?
Show answer
Use n ≈ 1.1774 × 2^(bits/2). With 40 bits, 2^20 = 1,048,576, so n ≈ 1.1774 × 1,048,576 ≈ 1.23 million items.
Exercise
Why does a 256-bit hash like SHA-256 give about 128 bits of collision resistance but about 256 bits of resistance to finding a preimage of a given digest?
Show answer
In a collision search the attacker may pick both inputs, so the birthday effect applies and the cost is about 2^(256/2) = 2^128. In a preimage search the target digest is fixed, so each guess matches with probability 1/2^256, and the cost is about 2^256.
Exercise
You plan to deduplicate 10 million files using a 64-bit hash of each file. Using the approximation, is the collision probability small enough to ignore? Give the number.
Show answer
Here n = 10^7 and m = 2^64 ≈ 1.8447 × 10^19. The exponent is n(n-1)/(2m) ≈ 10^14 / (3.69 × 10^19) ≈ 2.7 × 10^-6, so the probability is about 2.7 × 10^-6, roughly 1 in 370,000. That may be acceptable for casual use. For anything where a wrong match loses data, use a 128-bit or 256-bit hash.