Hunt a collision

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 bits bits 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 message and tries T on 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

Example 1 · Input
note 
16
Expected output
note 328
note 1044
tries 1045
Example 2 · Input
x
4
Expected output
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

Lesson: Why MD5 and SHA-1 are broken →