Sub topic 14
Hash flooding and randomized hashing
This chapter assumes you know how chaining and open addressing resolve collisions, and that you can read Big-O notation. It explains how an attacker can turn a hash table's O(1) average cost into O(n) per operation, and how randomized hashing prevents that.
Why the average case can be attacked
The O(1) average-case claim assumes keys spread roughly evenly across buckets. That is a statement about typical inputs, not about hostile ones. If an attacker knows your hash function, they can compute many distinct keys that land in the same bucket.
This is called hash flooding. Every colliding key lengthens one chain, or one probe sequence. Inserting n colliding keys then costs about n²/2 comparisons instead of n. A web server that stores request parameters or JSON keys in a hash table can be stalled this way by a single small request. This is a denial-of-service attack. It needs no bug in your code, only a predictable hash function.
A weak hash in action
Summing character codes is a poor hash. Every anagram of a word has the same sum, so every anagram collides. The code below inserts all 720 permutations of abcdef into 64 buckets, once with the weak hash and once with a keyed hash.
import hashlib
import itertools
import os
def weak_hash(s):
return sum(ord(c) for c in s)
def keyed_hash(s, key):
digest = hashlib.blake2b(s.encode(), key=key, digest_size=8).digest()
return int.from_bytes(digest, "big")
keys = ["".join(p) for p in itertools.permutations("abcdef")]
secret = os.urandom(16)
def longest_bucket(hash_fn, size=64):
counts = {}
for k in keys:
i = hash_fn(k) % size
counts[i] = counts.get(i, 0) + 1
return max(counts.values())
print(longest_bucket(weak_hash))
print(longest_bucket(lambda k: keyed_hash(k, secret)))The first line prints 720: every key shares one bucket. The second prints a small number, typically around 20, because the secret key makes the bucket for each string unpredictable.
Randomized hashing
The standard defense is to give each process, or each table, a secret random seed that is mixed into the hash function. The attacker can no longer precompute collisions, because the colliding keys depend on a value they cannot see.
Two details matter:
- The seed must be part of a hash that resists collision-finding. Adding a seed to the start of a simple polynomial hash, such as
h = seedbefore theh * 31 + ord(ch)loop, does not help. Two equal-length strings that collide with one seed collide with every seed. - Keyed hashes such as SipHash are designed for this. They are slower than a plain multiplicative hash on short keys, which is the trade-off. Python's
strandbyteshashing uses SipHash with a per-process seed.
A side effect is that iteration order of a hash set of strings can change between runs. Code must not depend on it.
Other mitigations
- Cap the number of keys accepted from untrusted input, such as request parameters.
- Use a table that degrades gracefully. Java's
HashMapconverts a long chain into a balanced tree, bounding the worst case at O(log n) when keys are comparable.
Exercise
A table uses chaining with a fixed, public hash function. An attacker sends 100,000 keys that all collide. Roughly how many key comparisons do the inserts cost, and why does a secret seed in a keyed hash change this?
Show answer
About n²/2, which is around 5 billion comparisons, because each insert scans the whole chain built so far. With a secret seed the attacker cannot choose keys that collide, so keys spread across buckets and the total cost returns to about n comparisons.