Belajar
← All lessons

How hashing works

Change one letter, change the whole hash

TextSame text, one letter changed
SHA-256
first
second

sha256.js

async function sha256(text) {  const bytes = new TextEncoder().encode(text);  const digest = await crypto.subtle.digest("SHA-256", bytes);  return [...new Uint8Array(digest)]    .map((b) => b.toString(16).padStart(2, "0")).join("");}

compare.js

const a = await sha256("hello");const b = await sha256("hellp"); // about half of the 256 bits flipconst flipped = countBits(xor(a, b));

Any input, same size one letter or a whole book

HashLetterSentenceParagraphBook
Input

SHA-256

Bars use a log scale. A million times more input, the same 32 bytes out

size.js

await sha256("a");await sha256(sentence);await sha256(paragraph);await sha256(await book.bytes()); // every digest is 32 bytes, 64 hex characters

Check a download against the published hash

Official site
You
Mirror

verify.js

// the official site publishes this next to the linkconst published = "3a7bd3e2…"; const file = await (await fetch(mirrorUrl)).arrayBuffer();const digest = hex(await crypto.subtle.digest("SHA-256", file)); if (digest !== published) {  throw new Error("checksum mismatch, don't run it");}run(file);

You can't undo a hash you can only guess

Leaked table
Attacker

crack.js

// check one guess(await sha256(guess)) === leaked; // or try a whole list of common passwordsfor (const word of wordList) {  if ((await sha256(word)) === leaked) return word;} // hash the list once, then look up any userfor (const w of wordList) table.set(await sha256(w), w);table.get(user.hash); // a random salt per user makes every hash newconst salt = randomHex(16);const hash = await sha256(salt + password);

Topics

Next: How SQL injection works

Open lesson