A fingerprint for any data
A hash function like SHA-256 turns any input into 256 bits. Same input, same hash; change one letter and about half the bits flip (the *avalanche effect*); and you can't work backwards. Git commit ids, download checksums and password storage all build on this. Browsers give you SHA-256 through crypto.subtle.
Hashing in the browser
async function sha256Hex(text) {
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
}
function bitsDifferent(hexA, hexB) {
let count = 0;
for (let i = 0; i < hexA.length; i++) {
let x = parseInt(hexA[i], 16) ^ parseInt(hexB[i], 16); // the bits that differ in this hex digit
while (x) {
count += x & 1;
x >>= 1;
}
}
return count;
}