Hash functions and the avalanche effect

Introduction

A hash function takes any amount of data (a word, a payment, a whole film) and squeezes it into a short value of fixed size, called the hash or digest. The same input always gives the same hash, and the smallest change gives a completely different one.

You have already met two weak hashes in this course: the checksum in the first lesson and the toy hash used for signatures. This lesson shows what a cryptographic hash such as SHA-256 adds, and why that one-way, unpredictable behaviour is the base of password storage, file checks, digital signatures and blockchains.

How it works

A cryptographic hash must have three properties, each stronger than the last:

PropertyMeansBreaks if
Preimage resistanceGiven a hash, you cannot find any input that makes itYou could "un-hash" a password
Second-preimage resistanceGiven an input, you cannot find another one with the same hashYou could swap a file for a fake with the same hash
Collision resistanceYou cannot find any two inputs with the same hashTwo different documents could share one signature

Two everyday behaviours come with these. It is deterministic: hashing the same text twice gives the same result, so you can compare. And it shows the avalanche effect: changing one bit of the input changes about half of the output bits, so similar inputs give hashes that look unrelated.

Try it below with real SHA-256, computed by your browser's Web Crypto API. Change one character in Text B and count the crossed cells: roughly half of the 256 bits flip every time.

A hash is not encryption. There is no key and no way back: you cannot "decrypt" a hash. That is exactly what makes it useful for storing passwords and checking files.

Example

FNV-1a is a small 32-bit hash used inside hash tables. It is not cryptographic, but it is short enough to follow step by step, and it shows the fixed size and a fair amount of avalanche.

// FNV-1a, a small, fast 32-bit hash (not a cryptographic one).
// Every input, short or long, gives exactly 8 hex digits.
function fnv1a(text) {
  let hash = 2166136261;
  for (let k = 0; k < text.length; k++) {
    hash = hash ^ text.charCodeAt(k);
    hash = Math.imul(hash, 16777619) >>> 0;
  }
  return hash.toString(16).padStart(8, "0");
}

function bitsDiffer(a, b) {
  let x = (parseInt(a, 16) ^ parseInt(b, 16)) >>> 0;
  let count = 0;
  while (x) {
    count += x & 1;
    x = x >>> 1;
  }
  return count;
}

console.log("a                 -> " + fnv1a("a"));
console.log("Pay 500 taka      -> " + fnv1a("Pay 500 taka"));
console.log("Pay 501 taka      -> " + fnv1a("Pay 501 taka"));
console.log("a whole paragraph -> " + fnv1a("Hashes squeeze any amount of text into a short, fixed-size value."));
console.log("bits that differ between the two payments: " + bitsDiffer(fnv1a("Pay 500 taka"), fnv1a("Pay 501 taka")) + " of 32");
Open in compiler

Line by line

  1. hash starts at FNV's fixed starting value, 2166136261.
  2. For each character, the hash is XOR-ed with the character's code, then multiplied by the FNV prime 16777619. Math.imul multiplies as 32-bit integers, and >>> 0 keeps the result a positive 32-bit number.
  3. The result is printed as 8 hex digits: one letter and a whole paragraph both give 8 digits.
  4. Pay 500 taka and Pay 501 taka differ in one character, yet their hashes share nothing visible: 17 of their 32 bits differ, close to half.

Expected result

a                 -> e40c292c
Pay 500 taka      -> d57ecea9
Pay 501 taka      -> 16edd958
a whole paragraph -> 5cfd7029
bits that differ between the two payments: 17 of 32

FNV-1a is fast and spreads values well, but it is easy to find inputs that collide on purpose, so it must never protect anything. SHA-256 is designed so that no such shortcut is known.

In the real world

  • Software sites publish a SHA-256 hash next to each download. The program below shows the check: hash what you received and compare.
  • Git names every file and commit by its hash, so any change to history changes the names.
  • Digital signatures sign the hash of a document, not the document itself, so a 500-page contract is signed as quickly as a one-line note.
  • Passwords are stored as hashes (with salt and a slow algorithm, two lessons from now), so a stolen database does not reveal them directly.
// Checking a download: the website publishes the file's hash; you hash what you received and compare.
function fnv1a(text) {
  let hash = 2166136261;
  for (let k = 0; k < text.length; k++) {
    hash = hash ^ text.charCodeAt(k);
    hash = Math.imul(hash, 16777619) >>> 0;
  }
  return hash.toString(16).padStart(8, "0");
}

const published = fnv1a("installer version 2.1, 48 MB of program code");
const downloads = [
  "installer version 2.1, 48 MB of program code",
  "installer version 2.1, 48 MB of program code + hidden extra",
];
for (const file of downloads) {
  console.log(fnv1a(file) === published ? "matches the published hash" : "DOES NOT match: do not run it");
}
Open in compiler

Common mistakes

  • Calling hashing encryption. A hash has no key and cannot be reversed; there is nothing to decrypt.
  • Using a fast, non-cryptographic hash for security. Hash-table hashes such as FNV are built for speed, not for resisting attackers.
  • Trusting a hash from the same place as the file. If an attacker changed the file on the website, they can change the hash beside it too; compare with a hash from a trusted source or a signature.
  • Expecting "similar input, similar hash". A good hash makes similar inputs look unrelated, so hashes cannot be used to find near-matches.

Best practices

  • Use SHA-256 or SHA-3 for integrity checks and signatures.
  • Never invent your own hash function.
  • Get the expected hash through a channel the attacker cannot change, such as a signed release page.
  • For passwords, use a password hash (bcrypt, scrypt or Argon2), not plain SHA-256.

Summary

A cryptographic hash maps any input to a fixed-size digest that is deterministic, one-way and collision resistant, and a one-bit change flips about half of its output bits. SHA-256 gives 256-bit digests and is used for file checks, signatures, Git and much more. A hash is not encryption: there is no key and no way back. Fast general-purpose hashes like FNV are fine for hash tables but must never protect anything.

Quick check

1. You change one letter of a long document and hash it again with SHA-256. What happens to the hash?
2. Which property stops an attacker from finding a second file with the same hash as a file you published?
3. Why can a hash not be "decrypted"?
4. Why is FNV-1a fine for a hash table but not for checking a download against attackers?

Key takeaways

  • A cryptographic hash is deterministic, fixed-size, one-way and collision resistant.
  • One changed bit of input flips about half of the hash's bits.
  • Hashing is not encryption: no key, no way back.
  • Use SHA-256 or SHA-3 for integrity, and never a fast hash-table hash for security.

Practice problems for this lesson

Was this lesson clear?

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.