Simple Algorithm
Algorithms & Data Structures · Optimal · 24 min

Hash Flooding & Anti-Hash Tests

Inputs that make hash tables quadratic, and the defenses against them.

In December 2011 a single web request whose form fields all collided in one hash bucket could keep a server's processor at 100% for a long time, on Java, PHP, Python, Ruby and more. The same trick still hacks contest solutions that trust std::unordered_map. This lesson shows how attackers manufacture collisions, what each defense actually guarantees, and how to write hash tables that a hostile test cannot break.

What you’ll learn

  • Model an algorithmic complexity attack and show that nn colliding insertions cost Θ(n2)\Theta(n^2) with chaining or linear probing.
  • Manufacture collisions for fixed hash functions: equal-hash blocks for polynomial string hashes, multiples of the bucket count for identity integer hashes, and birthday search for small moduli.
  • Compare the defenses (input limits, keyed hashing with SipHash, randomized seeds, tree-shaped buckets) by what each guarantees and what it assumes.
  • Write a contest-safe hash for std::unordered_map, and choose safe parameters for polynomial string hashing.

From O(1) to Θ(n²): algorithmic complexity attacks

Average-case bounds assume the keys do not depend on the hash function. An algorithmic complexity attack breaks exactly that assumption: the attacker knows the code, including the hash function hh, and chooses the keys. If the universe has more than (n−1) m(n-1)\,m keys, the pigeonhole principle guarantees nn keys with the same slot; the attacker's only job is to find them. This is hash flooding.

DerivationThe cost of n colliding keys
  1. ∑i=1n(i−1)=n(n−1)2=Θ(n2) comparisons\sum_{i=1}^{n} (i-1) = \frac{n(n-1)}{2} = \Theta(n^2) \text{ comparisons}

    Chaining. Every insertion scans the whole chain for a duplicate before appending, and the ii-th key finds i−1i - 1 keys there:

  2. ∑i=1ni=n(n+1)2=Θ(n2) probes\sum_{i=1}^{n} i = \frac{n(n+1)}{2} = \Theta(n^2) \text{ probes}

    Linear probing. The ii-th key with the same home slot probes the i−1i - 1 slots its predecessors took, plus one: n(n+1)/2n(n+1)/2 probes. Worse, every other key whose home falls inside that run of nn slots pays for it too.

  3. server workattacker work=Θ(n2)Θ(n)=Θ(n)\frac{\text{server work}}{\text{attacker work}} = \frac{\Theta(n^2)}{\Theta(n)} = \Theta(n)

    Amplification. The attacker sends nn keys, the server does Θ(n2)\Theta(n^2) work: each byte sent buys Θ(n)\Theta(n) units of work. That ratio is what makes a modest request dangerous.

Think first A server inserts 216=65,5362^{16} = 65{,}536 attacker-chosen keys, all with the same hash, into a chained table that scans each chain for duplicates. How many key comparisons does it make?

65,536⋅65,535/2=2,147,450,88065{,}536 \cdot 65{,}535 / 2 = 2{,}147{,}450{,}880: about 2.15 billion string comparisons, seconds of processor time, triggered by one request. Spread by a good hash function, the same keys would cost about 65,536 comparisons.

Manufacturing collisions

Pigeonhole guarantees that colliding keys exist; structure makes them cheap to find. Three recipes cover most real attacks.

Equal-hash blocks. A polynomial hash H(s)=∑ici bL−1−i mod 232H(s) = \sum_i c_i\,b^{L-1-i} \bmod 2^{32} satisfies H(uv)=H(u) b∣v∣+H(v)H(uv) = H(u)\,b^{\abs v} + H(v). So if two blocks of the same length have the same hash, they can be swapped anywhere without changing the total. Java's String.hashCode uses b=31b = 31, and "Aa" and "BB" both hash to 65⋅31+97=66⋅31+66=211265 \cdot 31 + 97 = 66 \cdot 31 + 66 = 2112. Bernstein's times-33 hash, used by PHP for its arrays, has the pair "Ez" and "FY" (69⋅33+122=70⋅33+89=239969 \cdot 33 + 122 = 70 \cdot 33 + 89 = 2399). Concatenating kk blocks gives 2k2^k colliding strings of length 2k2k.

python
from itertools import product

def java_hash(s):                            # Java's String.hashCode: 31-polynomial modulo 2**32
    h = 0
    for ch in s:
        h = (31 * h + ord(ch)) % 2**32
    return h - 2**32 if h >= 2**31 else h

assert java_hash('Aa') == java_hash('BB') == 2112          # 65*31 + 97 == 66*31 + 66

def colliding(k):                            # 2**k strings of length 2k with one hash
    return [''.join(blocks) for blocks in product(['Aa', 'BB'], repeat=k)]

keys = colliding(16)
print(len(keys), len({java_hash(s) for s in keys}))        # 65536 1

65,536 field names of 32 characters, one hash value: about 2 MB of parameters that force the 2.15 billion comparisons of the question above.

Identity hashes on integers. GCC's libstdc++ and LLVM's libc++ hash an integer to itself, and std::unordered_map takes the remainder by a prime bucket count that the library chooses deterministically as the table grows. Run the same compiler, read bucket_count() after nn insertions, and insert multiples of that prime: they all land in bucket 0. Python randomizes the hashes of str and bytes, but not of int: a non-negative integer hashes to its value modulo 261−12^{61} - 1, so every multiple of 261−12^{61} - 1 hashes to 0, and set(i * (2**61 - 1) for i in range(20000)) takes seconds where random integers take about a millisecond.

Birthday search. A fixed polynomial hash modulo a prime p≈109p \approx 10^9 with a known base can be attacked by brute force: by the birthday paradox, random strings collide after about πp/2≈40,000\sqrt{\pi p/2} \approx 40{,}000 tries. With base 131, modulus 109+710^9 + 7 and characters taken as their ASCII codes, the strings aumfgtqczm and wpoozwisuz both hash to 463,473,016. And arithmetic modulo 2642^{64} fails for every odd base on the Thue–Morse strings, as the Optimal lesson Polynomial Hashing in Depth proves.

Defenses, and what each one guarantees

DefenseWhat it guaranteesWhat it assumes or costs
Cap the input (number of form fields, of keys per request)Bounds nn, hence the n2n^2Treats the symptom; every entry point needs its own cap
Draw hh at random from a universal family at startupExpected O(1+α)O(1 + \alpha) per operation for every input fixed in advanceThe keys must not depend on hh: timing or iteration order can leak it to an adaptive attacker
Keyed hash with a secret random key, such as SipHashFinding collisions is as hard as breaking a pseudorandom functionA cryptographic assumption, not a theorem; slower than unkeyed hashes on short keys
Tree-shaped buckets (Java's HashMap since Java 8)O(log⁡n)O(\log n) per operation in the worst case, if colliding keys are Comparable or have distinct hashesNeeds an order on the keys; does nothing for open addressing
An ordered structure (balanced search tree)O(log⁡n)O(\log n) worst case, no hashing at allA logarithmic factor on every operation
Real systems combine them: Python hashes strings and bytes with SipHash-1-3 under a random per-process key (setting PYTHONHASHSEED fixes the key for reproducible runs, and 0 disables randomization), Rust's HashMap hashes every key type with SipHash-1-3 under a random per-map key, and Java keeps a deterministic String.hashCode but turns long chains into trees. PEP 456 lists Ruby, Perl, Redis and FreeBSD among other adopters of SipHash.
DerivationWhy a secret key removes the amplification
  1. Pr⁡[hK(x)=j]=1mfor every key x not yet observed\Pr\big[h_K(x) = j\big] = \frac1m \quad \text{for every key } x \text{ not yet observed}

    Model the keyed hash as a random function the attacker cannot see. Then every fresh key lands in a given slot with probability 1/m1/m, whatever the attacker does:

  2. E[keys sent]≈n m,E[server work]=O(nm (1+α))\E[\text{keys sent}] \approx n\,m, \qquad \E[\text{server work}] = O\big(nm\,(1 + \alpha)\big)

    To pile nn keys into one slot the attacker must therefore send about nmnm keys, and those cost the server only O(1+α)O(1 + \alpha) expected work each:

  3. server workattacker work=O(1+α)\frac{\text{server work}}{\text{attacker work}} = O(1 + \alpha)

    The server's work is proportional to the attacker's, as for any honest traffic: the Θ(n)\Theta(n) amplification of a fixed hash function is gone. The argument breaks only if the attacker learns about hKh_K, which is why a weak seeded hash, or one that leaks its secret, is not enough.

Check your understanding

A Python 3.12 web service stores user-supplied numeric IDs, converted with int(), as keys of a dict. Is it protected from hash flooding by Python's hash randomization?

  1. Yes: every dict is seeded with a random key at startup
  2. Yes: dict uses open addressing, which cannot be flooded
  3. No: randomization covers str and bytes, and an int hashes to its value modulo 261−12^{61} - 1, so multiples of 261−12^{61} - 1 all collide
  4. No: Python never randomizes any hash
Show the answer

C. No: randomization covers str and bytes, and an int hashes to its value modulo 261−12^{61} - 1, so multiples of 261−12^{61} - 1 all collide

Python's random key is applied to str and bytes. Integers hash deterministically, so an attacker can send IDs that all hash to 0. Keep such IDs as strings, combine them with a secret salt before using them as keys, or cap how many a request may create.

Anti-hash tests in competitive programming

On judges with a hacking phase, rivals read your accepted code and submit tests designed against it, and std::unordered_map<long long, …> with the default hash is a favorite target: the hash is the identity and the bucket counts are predictable, so a test of about 10510^5 multiples of the right prime turns your O(n)O(n) solution into Θ(n2)\Theta(n^2). On one laptop with LLVM's libc++, inserting 200,000 multiples of the final bucket count took about 26 seconds, against about 0.01 seconds for random keys. Calling reserve does not help: it just makes the bucket count, and therefore the right prime, easier to predict.

The fix is to hash with a function the hacker cannot predict, seeded when your program runs, after the test was written:

cpp
#include <chrono>
#include <cstdint>
#include <unordered_map>

struct custom_hash {
    static uint64_t splitmix64(uint64_t x) {         // the finalizer of the splitmix64 generator
        x += 0x9e3779b97f4a7c15;
        x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
        x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
        return x ^ (x >> 31);
    }
    size_t operator()(uint64_t x) const {
        static const uint64_t SEED =                 // fixed when the program starts
            std::chrono::steady_clock::now().time_since_epoch().count();
        return splitmix64(x + SEED);
    }
};

std::unordered_map<long long, int, custom_hash> safe_map;   // drop-in replacement

The mixing function is the output stage of Vigna's splitmix64 generator (a fixed-increment version of Java's SplittableRandom); its first constant is ⌊264/φ⌋\lfloor 2^{64}/\varphi \rfloor, the multiply-shift constant of the Optimized lesson Hash Tables. On the 200,000-key attack above it brought the time back to about 0.01 seconds. It is fast and mixes all 64 bits, but it is not cryptographic: it defeats tests fixed in advance, not an attacker who can watch your table.

Strings deserve the same care. For polynomial hashing, draw the base at random when the program starts, and use a large prime modulus such as 261−12^{61} - 1 (or two independent moduli near 10910^9); never rely on the free overflow modulo 2642^{64}. Then two distinct strings of length nn collide with probability at most (n−1)/p(n-1)/p, whatever the test. In Python, integer keys read from the input can be stored as strings or combined with a random salt; on 20,000 multiples of 261−12^{61} - 1, XOR with a random 64-bit salt cut the time of building a set from seconds to about a hundredth of a second.

Check your understanding

Your C++ solution stores up to 2×1052 \times 10^5 long long keys in std::unordered_map with the default hash, and the contest allows hacking. Which change protects it while keeping expected O(1)O(1) operations?

  1. Call reserve(1 << 18) before inserting
  2. Hash with splitmix64(x + SEED), where SEED is read from the clock when the program starts
  3. Hash with h(x)=31x+7h(x) = 31x + 7 instead of the identity
  4. Set max_load_factor(0.25) so the buckets stay short
Show the answer

B. Hash with splitmix64(x + SEED), where SEED is read from the clock when the program starts

The hacker must fix the test before your program runs, and cannot predict a seed drawn at run time; splitmix64 then spreads any fixed set of keys like random ones. Switching to std::map would also be safe, at O(log⁡n)O(\log n) per operation.

Key takeaways

  • With a fixed, public hash function an attacker makes nn insertions cost Θ(n2)\Theta(n^2), an amplification of Θ(n)\Theta(n) over the attacker's own work (Crosby & Wallach, 2003; the 2011 web-platform advisories).
  • Colliding keys come from structure: equal-hash blocks for polynomial hashes ("Aa" and "BB" in Java), multiples of the bucket count for identity integer hashes, birthday search for small moduli, and seed-independent collisions in weak seeded hashes.
  • Keyed hashing with a secret random key (SipHash in Python, Rust and many others) makes flooding as expensive as random guessing, under a cryptographic assumption; tree bins (Java 8) cap the damage at O(log⁡n)O(\log n) per operation.
  • In contests, give unordered_map a hash such as splitmix64(x + SEED) with a run-time seed, use a random base and a large prime modulus for string hashing, and remember that Python randomizes only str and bytes.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

"Aa" and "BB" have the same Java hashCode. How many distinct strings of length 20 with one common hash can you build by concatenating these blocks?

  1. 20
  2. 200
  3. 1,024
  4. 202=40020^2 = 400
Show the answer

C. 1,024

A string of length 20 is 10 blocks, each chosen independently from two options: 210=10242^{10} = 1024 strings. Because H(uv)=H(u) 31∣v∣+H(v)H(uv) = H(u)\,31^{\abs v} + H(v), swapping equal-hash blocks of equal length never changes the total.

Question 2

A Java 8+ HashMap<String, V> receives 10510^5 distinct keys that all have the same hashCode. About how much work do the insertions take in total?

  1. Θ(n2)\Theta(n^2), as in any chained table
  2. Θ(nlog⁡n)\Theta(n \log n): the bin becomes a red-black tree ordered by compareTo
  3. Θ(n)\Theta(n): Java rehashes with a random seed when a chain gets long
  4. The map throws an exception once a bin holds 8 keys
Show the answer

B. Θ(nlog⁡n)\Theta(n \log n): the bin becomes a red-black tree ordered by compareTo

Once a bin holds 8 entries (in a table of at least 64 bins), Java converts it to a red-black tree. Strings are Comparable, so the tree is ordered by compareTo, and each insertion costs O(log⁡n)O(\log n) comparisons.

Question 3

A solution hashes strings with a fixed, published base and the prime modulus p=109+7p = 10^9 + 7. About how many random strings must a hacker hash before two of them collide?

  1. About 30
  2. About 40,000
  3. About 10910^9
  4. About 101810^{18}
Show the answer

B. About 40,000

By the birthday bound, collisions among random hash values appear after about πp/2≈39,600\sqrt{\pi p/2} \approx 39{,}600 draws, a fraction of a second of computing. A random base drawn at run time, or a modulus near 2612^{61}, defeats this.

Further reading

  • S. A. Crosby & D. S. Wallach, "Denial of service via algorithmic complexity attacks," Proceedings of the 12th USENIX Security Symposium (2003).
  • oCERT, "oCERT-2011-003: multiple implementations denial-of-service via hash algorithm collision" (advisory, December 28, 2011).
  • J.-P. Aumasson & D. J. Bernstein, "SipHash: a fast short-input PRF," INDOCRYPT (2012).
  • C. Heimes, "PEP 456: Secure and interchangeable hash algorithm" (Python Enhancement Proposal, 2013).
  • J. Pachocki & J. Radoszewski, "Where to use and how not to use polynomial string hashing," Olympiads in Informatics 7 (2013), 90–100.