Created
October 1, 2021 16:55
-
-
Save subzey/3f1a0efd1634bdf0b03ba2a2e744bc3e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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