Skip to content

Instantly share code, notes, and snippets.

@subzey
Created October 1, 2021 16:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save subzey/3f1a0efd1634bdf0b03ba2a2e744bc3e to your computer and use it in GitHub Desktop.
Save subzey/3f1a0efd1634bdf0b03ba2a2e744bc3e to your computer and use it in GitHub Desktop.
const { createHash } = require('crypto');
const hashFunction = 'sha256';
const hashDigest = 'base64';
const hashDigestLength = 5;
function currentImplementation(content, hashSalt) {
const hash = createHash(hashFunction);
if (hashSalt) {
hash.update(hashSalt);
}
hash.update(content);
const localIdentHash = hash
.digest(hashDigest)
.slice(0, hashDigestLength)
.replace(/[/+]/g, "_")
.replace(/^\d/g, "_")
;
return localIdentHash;
}
function proprosedImplementation(content, hashSalt) {
let localIdentHash = '';
for (const tierSalt = Uint32Array.of(0); localIdentHash.length < hashDigestLength; tierSalt[0]++) {
const hash = createHash(hashFunction);
if (hashSalt) {
hash.update(hashSalt);
}
hash.update(tierSalt);
hash.update(content);
localIdentHash = (localIdentHash + hash.digest(hashDigest))
.replace(/^\d+/, "")
.slice(0, hashDigestLength)
.replace(/[/]/g, "_")
.replace(/[+]/g, "-")
;
}
return localIdentHash;
}
function hashesUntilCollision(hasher, salt) {
const set = new Set();
for (let i = 1; ; i++) {
const localIdHash = hasher(`Some string used as content #${i}`, salt);
if (set.has(localIdHash)) {
return i;
}
set.add(localIdHash);
}
}
function medianHashesUntilCollision(hasher) {
let results = [];
for (let i = 0; i < 101; i++) {
results.push(hashesUntilCollision(hasher, String(i)));
}
results.sort((a, b) => a - b);
return results[Math.floor(results.length / 2)];
}
console.log('Current', medianHashesUntilCollision(currentImplementation));
console.log('Proposed', medianHashesUntilCollision(proprosedImplementation));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment