TExcelTAD
Home › Applied Cryptography: Ciphers, Hashes, Signatures, PKI & TLS › Hash Function Properties and the Birthday Bound

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 HH 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 nn-bit digest, the security goals are:

Property The attacker is given and must find Generic cost
preimage resistance (one-way) a digest dd any mm with H(m)=dH(m) = d 2n2^n
second-preimage resistance a message m1m_1 a different m2m_2 with H(m2)=H(m1)H(m_2) = H(m_1) 2n2^n
collision resistance nothing any pair m1≠m2m_1 \ne m_2 with H(m1)=H(m2)H(m_1) = H(m_2) 2n/22^{n/2}

"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 kk people form k(k−1)/2k(k-1)/2 pairs. For a hash with N=2nN = 2^n equally likely outputs, the probability of at least one collision among kk random inputs is

p(k)≈1−e−k(k−1)/(2N)≈k22Nfor small pp(k) \approx 1 - e^{-k(k-1)/(2N)} \approx \frac{k^2}{2N} \quad \text{for small } p

Setting p=12p = \frac{1}{2} gives k≈1.18Nk \approx 1.18\sqrt{N}, and the expected number of hashes until the first collision is

E[k]≈π2N=π2 2n/2≈1.25×2n/2E[k] \approx \sqrt{\frac{\pi}{2} N} = \sqrt{\frac{\pi}{2}} \, 2^{n/2} \approx 1.25 \times 2^{n/2}

So collisions cost about 2n/22^{n/2} hash evaluations: 2642^{64} for a 128-bit digest such as MD5 (within reach of large computations even without MD5's weaknesses) and 21282^{128} 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.

python · try it yourself
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] = i
sha256('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 2202^{20}, 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 n load 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: nn bits of digest give about n/2n/2 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 N=232N = 2^{32} and a collision is likely after about 1.18232=1.18×2161.18\sqrt{2^{32}} = 1.18 \times 2^{16}, 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?

244/2/240/2=22=42^{44/2} / 2^{40/2} = 2^2 = 4 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 nn-bit hash need?

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

Which property do digital signatures depend on most?

  1. Preimage resistance
  2. Collision resistance
  3. Speed
  4. Length extension

In the example, how many hashes did the 40-bit collision search take?

  1. About 1 million
  2. About 2 million
  3. About 1 trillion
  4. Exactly 2402^{40}

What collision security does SHA-256 give?

  1. 256 bits
  2. 128 bits
  3. 64 bits
  4. 32 bits