Hash Function Properties and the Birthday Bound
Cryptographic hash functions are everywhere in security work: file-integrity monitoring, package lockfiles, Git commits, certificate signatures, password storage, HMAC, blockchains, deduplication. Each of those uses relies on a specific property of the hash, and the properties have very different strengths. The most important number in this lesson is a surprise to most people: a 256-bit hash gives only 128 bits of security against collisions.
What a hash function is
A hash function maps input of any length to a fixed-size digest, for SHA-256 256 bits (32 bytes, 64 hex digits). It is public and has no key: anyone can compute it. For an -bit digest, the security goals are:
| Property | The attacker is given | and must find | Generic cost |
|---|---|---|---|
| preimage resistance (one-way) | a digest | any with | |
| second-preimage resistance | a message | a different with | |
| collision resistance | nothing | any pair with |
"Generic cost" is what brute force costs against an ideal hash. A hash is considered broken for a property when an attack does significantly better than that number, as happened to MD5 and SHA-1 for collisions (MD5 and SHA-1).
Which property does each use need?
- Verifying a download against a published SHA-256: second-preimage resistance (the attacker must match an existing file).
- Signatures and certificates: collision resistance, because the attacker may prepare both documents, get one signed and swap in the other.
- Commitments and Git object ids: collision resistance.
- Password storage: preimage resistance, plus slowness and salts, which ordinary hashes don't provide.
The birthday bound
In a room of 23 people, the chance that two share a birthday is above one half, although there are 365 days. The reason is that a collision can happen between any pair, and people form pairs. For a hash with equally likely outputs, the probability of at least one collision among random inputs is
Setting gives , and the expected number of hashes until the first collision is
So collisions cost about hash evaluations: for a 128-bit digest such as MD5 (within reach of large computations even without MD5's weaknesses) and for SHA-256. The derivation is in The Birthday Bound.
Both searches on toy hashes
Real digests are far too long to search, so the example truncates SHA-256 to toy sizes: 20 bits for a preimage search and 40 bits for a collision search. The point is the difference in cost: the collision on a hash twice as long takes about the same work as the preimage on the short one.
import hashlib, math
def h(msg, bits): # SHA-256 truncated to `bits` bits: a toy hash with a tiny output
return int.from_bytes(hashlib.sha256(msg).digest(), "big") >> (256 - bits)
print("sha256('abc') =", hashlib.sha256(b"abc").hexdigest()[:32], "...")
# Preimage on a 20-bit toy: find any message with the same hash as the target.
target = h(b"the target message", 20)
for i in range(1, 10**7):
if h(b"try %d" % i, 20) == target:
print(f"20-bit preimage after {i:,} tries (expected about 2^20 = {2**20:,})")
break
# Collision on a 40-bit toy: any two messages with the same hash (birthday search).
seen = {}
for i in range(1, 10**8):
d = h(b"msg %d" % i, 40)
if d in seen:
print(f"40-bit collision after {i:,} hashes: 'msg {seen[d]}' and 'msg {i}'")
print(f"birthday estimate sqrt(pi/2 * 2^40) = {math.sqrt(math.pi / 2 * 2**40):,.0f}")
break
seen[d] = isha256('abc') = ba7816bf8f01cfea414140de5dae2223 ...
20-bit preimage after 1,683,250 tries (expected about 2^20 = 1,048,576)
40-bit collision after 1,965,946 hashes: 'msg 542861' and 'msg 1965946'
birthday estimate sqrt(pi/2 * 2^40) = 1,314,195
The preimage on 20 bits took about 1.7 million tries (the expected value is , about a million, with a lot of spread). The collision on 40 bits took about 2.0 million hashes, close to the birthday estimate of 1.3 million. A 40-bit preimage would have needed about a trillion tries. That factor is why digest sizes are chosen with collisions in mind: for 128-bit collision security you need a 256-bit hash.
The collision search stored every digest in a dictionary, so it also needed memory proportional to the work. Real collision searches use cycle-finding methods (Pollard's rho, parallel distinguished points by van Oorschot and Wiener) that need almost no memory, so memory is no defence.
Other properties you may rely on
- Pseudorandom output: digests look uniformly random; used by key derivation and
hash(x) mod nload balancing. - Avalanche: changing one input bit flips about half the output bits (the next lesson's lab).
- No length extension: SHA-256 and SHA-512 fail this one, which matters when a hash is used with a secret (Length Extension).
How weak hash use is detected
- Digest size versus need: truncated digests (
sha256(...)[:8], 32-bit ids, CRC32 or a 64-bit hash used as a unique id or integrity check) are cheap to collide; flag anything under 128 bits for collision-sensitive uses and under 256 bits where 128-bit collision security is required. - Broken algorithms: MD5 or SHA-1 in signatures, certificates, code signing, lockfiles, deduplication of untrusted content.
- Non-cryptographic hashes (CRC32, MurmurHash, xxHash, Python's
hash()) used for security decisions: fast and fine for hash tables, trivially colliding by design.
How it is fixed
- Use SHA-256, SHA-512/256, SHA-3 or BLAKE2/BLAKE3 at full length for integrity and identifiers.
- Choose the output length from the collision bound: bits of digest give about bits of collision security.
- Use a keyed construction (HMAC) whenever a secret is involved, and a password hash (Argon2id) for passwords.
Pitfalls
- Assuming "256-bit hash" means 256-bit security against every attack. Collisions: 128 bits. Against quantum search, preimages too fall to about 128 bits.
- Truncating a digest to make a short id and then treating it as unique for untrusted input.
- Treating a hash as a MAC: anyone can recompute it.
Practice
1. A system tags uploaded files with the first 8 hex digits of their SHA-256 as a unique id. How many uploads until a collision is likely?
8 hex digits are 32 bits, so and a collision is likely after about , roughly 77,000 files. An attacker who wants a collision can produce one in seconds. Use the full digest.
2. Which property must SHA-256 have so that a published hash protects a software download?
Second-preimage resistance: given the genuine file, the attacker must not find a different file with the same digest. (If the attacker can influence the genuine file too, collision resistance is needed.)
3. Modify the example to search for a 44-bit collision. How much more work do you expect than for 40 bits?
times as many hashes, about 5 million on average. Four extra bits of digest cost only a factor 4 for collisions but 16 for preimages.
Test yourself
How many hash evaluations does a generic collision search on an -bit hash need?
- About
- About
- About
- About
Which property do digital signatures depend on most?
- Preimage resistance
- Collision resistance
- Speed
- Length extension
In the example, how many hashes did the 40-bit collision search take?
- About 1 million
- About 2 million
- About 1 trillion
- Exactly
What collision security does SHA-256 give?
- 256 bits
- 128 bits
- 64 bits
- 32 bits