Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save phillipharding/7e25fcd8582d2975e1a87c8fb72fbcae to your computer and use it in GitHub Desktop.

Select an option

Save phillipharding/7e25fcd8582d2975e1a87c8fb72fbcae to your computer and use it in GitHub Desktop.
A Node.js typescript function that produces a unique hash based on an input string and optional seed, using the Shake265 algorithm

Hash Collision Risk Analysis (15,000 Items) using the SHAKE256 Algorithm

The following table illustrates the probability of at least one collision occurring within a dataset of 15,000 unique inputs based on the hexadecimal character length.

Hex Length Total Combinations Prob. of Collision Risk Level Safety Context
8 $4.29 \times 10^9$ ~2.6% 🔴 High 1 in 38 chance; unsafe for production.
10 $1.09 \times 10^{12}$ ~0.01% 🟡 Moderate 1 in 10,000 chance; risky for primary keys.
12 $2.81 \times 10^{14}$ ~0.00004% 🟢 Low 1 in 2.5 million; very safe for most apps.
14 $7.20 \times 10^{16}$ < 0.0000001% 🔵 Safe 1 in 1 billion; negligible risk.
16 $1.84 \times 10^{19}$ ~$10^{-11}$ 🛡️ Ultra 1 in 80 trillion; industry standard.

Risk calculated using the Birthday Paradox approximation: $P \approx 1 - e^{-n^2 / 2H}$ where $n=15,000$.

import { createHash } from 'node:crypto';
/**
* Generate a deterministic hex hash of a specific length.
* @param input - The string to hash.
* @param seed - Optional seed to vary the output.
* @param length - The desired hex character length (default to 10).
*/
export function generateUniqueHash(input: string, seed: string = '', length: number = 10): string {
// each byte yields 2 hex characters, support odd-numbered lengths.
const byteLength = Math.ceil(length / 2);
return createHash('shake256', { outputLength: byteLength })
.update(seed + input)
.digest('hex')
.slice(0, length); // ensure exact length if an odd length was requested
}
// Usage:
console.log(generateHash("user_123")); // "4f2d1a3c5e" (Default 10)
console.log(generateHash("user_123", "v2", 8)); // "a1b2c3d4" (Requested 8)
console.log(generateHash("user_123", "", 14)); // "7f8e9d0c1b2a3d" (Safe for 15k+ items)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment