Sikau

Security · Day 5 · about 35 min

Hash functions

SHA-256: fixed-size fingerprints, one-way, and wildly different for tiny changes.

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;
}

The rest of this lesson

  • Three propertiesexplain
  • Hashes in everyday toolsexplain
  • Hashes are used for…match
  • Hash lengthpredict
  • Hash and comparewrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 8 lessons of Security