Sub topic 14
When Inputs Fight Back: Anti-Hash Tests
This chapter assumes you already know the polynomial hash, the rolling update, Rabin-Karp with match verification, and double hashing from earlier chapters. Up to now we treated input as if it were random. That assumption fails when someone picks the input on purpose to break your hash. Inputs built this way are called anti-hash tests. Programming contest judges use them to break hacked solutions, and attackers have used the same idea against hash tables in web servers, which is known as hash flooding.
The working model: fixed parameters are public information
Suppose the base and modulus are constants in your source code, as in base=256, mod=1_000_000_007. Anyone who can read the code, or guess the usual defaults, can search offline for two different strings with the same hash. The program has nothing random left in it, so a collision that the attacker finds once will work every time the program runs.
The damage depends on how you handle a hash match:
| Your code | Effect of a forced collision |
|---|---|
| Verifies every hash match | Still correct. Each false match costs O(m), so many of them push the running time toward O(nm). |
| Trusts hash equality | Wrong answers: false matches, or wrong results for "are these substrings equal?" |
Attack 1: the birthday search against a known prime
A modulus near 10^9 has about 10^9 possible hash values. The birthday bound says that after hashing about √(π/2 · 10^9) ≈ 40,000 random strings, you should expect two of them to share a hash. That takes a fraction of a second.
import random
def poly_hash(s, base=256, mod=1_000_000_007):
h = 0
for ch in s:
h = (h * base + ord(ch)) % mod
return h
def find_collision(base=256, mod=1_000_000_007, length=8, seed=1):
rng = random.Random(seed)
alphabet = "abcdefghijklmnopqrstuvwxyz"
seen = {}
tries = 0
while True:
s = "".join(rng.choice(alphabet) for _ in range(length))
tries += 1
h = poly_hash(s, base, mod)
if h in seen and seen[h] != s:
return seen[h], s, tries
seen[h] = s
a, b, tries = find_collision()
print(a, b, tries)
print(poly_hash(a) == poly_hash(b), a != b) # True TrueAfter finding one colliding pair, the attacker can build a long text that repeats one string and a pattern that is the other. If your code trusts the hash, it reports a match at every window that holds the wrong string.
Attack 2: Thue–Morse strings against modulus 2^64
A common shortcut is to skip the % and let unsigned 64-bit arithmetic wrap around, which is the same as computing modulo 2^64. A Thue–Morse string and its complement (with a and b swapped) collide under this hash for every odd base. The hash difference factors into terms of the form (b^(2^i) − 1). For odd b, these terms together contain more than 64 factors of 2, so the difference is 0 modulo 2^64.
import random
MASK = (1 << 64) - 1
SWAP = str.maketrans("ab", "ba")
def hash64(s, base):
h = 0
for ch in s:
h = (h * base + ord(ch)) & MASK
return h
def thue_morse(k):
s = "a"
for _ in range(k):
s = s + s.translate(SWAP)
return s
s = thue_morse(11) # length 2048
t = s.translate(SWAP)
for base in (31, 131, 1_000_003, random.randrange(1, 1 << 62) | 1):
print(base, hash64(s, base) == hash64(t, base)) # always TrueRandomizing the base does not help here, because the attack works for every odd base. The weakness comes from the modulus.
Defenses that work
- Use a prime modulus, preferably a large one such as 2^61 − 1. Do not rely on wraparound modulo 2^64.
- Pick the base at random each time the program runs, for example
random.randrange(256, mod - 1). An attacker who prepares input in advance cannot know the base. Any fixed pair of different strings of length m then collides with probability at most (m − 1)/mod. - Use double hashing with two independent random bases if you skip verification. The chance of a collision becomes roughly the product of the two single-hash probabilities.
- Verify matches when correctness matters. Verification turns a collision into a slowdown instead of a wrong answer.
Exercise
A solution uses base 131 and lets unsigned 64-bit arithmetic overflow. The author switches to a random odd base chosen at runtime. Is the solution now safe against anti-hash tests? Why or why not?
Show answer
No. The Thue–Morse string of length 2048 and its complement collide modulo 2^64 for every odd base, so a random base does nothing against this attack. The fix is to change the modulus to a large prime such as 2^61 − 1 and keep the base random.
Exercise
Your Rabin-Karp verifies every hash match, but uses the fixed parameters base=256 and mod=1000000_007. What is the worst an attacker can do, and how do you stop it?
Show answer
The attacker cannot cause wrong answers. They can use a birthday-found collision to force a false hash match at many windows, and each one costs an O(m) comparison, so the total time grows toward O(nm). Choosing the base at random at runtime stops this, because the attacker can no longer predict which strings collide.