Cut a hash down to a few bits and collisions come quickly. This is the birthday attack in miniature.
What to build
Hash messages prefix0, prefix1, … with FNV-1a cut to a number of bits, and report the first collision.
Requirements
- FNV-1a 32-bit: start at 2166136261; for each character, XOR the hash with the character code, then multiply by 16777619 keeping 32 bits (
Math.imul(hash, 16777619) >>> 0). - Keep only the lowest
bitsbits of the 32-bit hash:hash & (2^bits − 1)(for 32 bits, keep the whole hash). - Messages are the prefix followed by 0, 1, 2, … with no space.
- At the first message whose cut hash was already seen, print
first message,second messageandtries Ton three lines, where T counts every message hashed.
Input
Line 1: the prefix. Line 2: bits.
Output
Three lines.
Constraints
1 ≤ bits ≤ 24. The prefix has 1 to 20 characters.
Example
Input:
note
16
Output:
note 328
note 1044
tries 1045
Why it works
Remembering every cut hash in a map finds a repeat as soon as it happens, and by the birthday bound that takes about √(2^bits) messages, far fewer than the number of possible hashes.
Examples
note 16
note 328 note 1044 tries 1045
x 4
x5 x10 tries 11
Hints
Hint 1
Use a Map from cut hash to the message that produced it.
Hint 2
(h & mask) >>> 0 keeps the value non-negative; for bits = 32 you can skip the mask.
Solution
Show one correct solution (try it yourself first)
function fnv32(text) {
let hash = 2166136261;
for (let k = 0; k < text.length; k++) {
hash = hash ^ text.charCodeAt(k);
hash = Math.imul(hash, 16777619) >>> 0;
}
return hash;
}
const prefix = prompt();
const bits = Number(prompt());
const mask = bits >= 32 ? 0xffffffff : 2 ** bits - 1;
const seen = new Map();
for (let n = 0; ; n++) {
const message = prefix + n;
const h = (fnv32(message) & mask) >>> 0;
if (seen.has(h)) {
console.log(seen.get(h));
console.log(message);
console.log(`tries ${n + 1}`);
break;
}
seen.set(h, message);
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step