11. Hash Functions & MACs
One-way fingerprints for data integrity
Encryption protects confidentiality — but what about integrity? How do you know a message wasn't tampered with in transit? How does a server prove the file you downloaded is the file it published? Hash functions answer these questions. They produce a fixed-size "fingerprint" of any input, no matter how large. Change even one bit and the fingerprint changes completely.
What Is a Hash Function?
A hash function takes an arbitrary-length input and produces a fixed-size output called a digest (or simply a hash). Three properties make it useful:
- Deterministic — the same input always produces the same output
- Fast to compute — hashing a gigabyte of data takes seconds, not hours
- One-way — given a hash, you can't recover the original input
The avalanche effect in SHA-256
Input: "Hello, world!"
SHA-256: 315f5bdb76d078c43b8ac0064e4a0164612b1fce77c869345bfc94c75894edd3
Input: "Hello, World!" (capital W — one bit changed)
SHA-256: dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f
One character changed and every byte of the hash is different. This is the avalanche effect: a tiny change in the input cascades into a completely different output. There is no way to predict how the hash will change.
Cryptographic Hash Properties
Not every hash function is suitable for cryptography. A cryptographic hash function must satisfy three essential properties:
-
Preimage resistance
Given a hash value h, it is infeasible to find any input m such that H(m) = h. You can't reverse the function. If someone gives you a hash, you cannot work backwards to discover what was hashed.
-
Second preimage resistance
Given an input m₁, it is infeasible to find a different input m₂ ≠ m₁ such that H(m₁) = H(m₂). You can't find a substitute that hashes to the same value as a known document. This prevents forgery: an attacker can't swap in a malicious file that matches the hash of a legitimate one.
-
Collision resistance
It is infeasible to find any two distinct inputs m₁ ≠ m₂ with H(m₁) = H(m₂). This is stronger than second preimage resistance — the attacker gets to choose both inputs freely.
The Birthday Paradox and Collision Resistance
Birthday attacks halve your security level
For a hash with an n-bit output, finding a collision takes approximately 2n/2 attempts — not 2n. This is why SHA-256, with its 256-bit output, provides 128-bit collision resistance, not 256-bit.
The intuition comes from the birthday paradox: in a room of just 23 people, there is a 50% chance that two share a birthday — even though there are 365 possible birthdays. You don't need to match a specific person's birthday; you just need any pair to collide. The same logic applies to hash outputs. Because collisions involve pairs, the number of attempts needed scales with the square root of the output space, not the full space. For a 128-bit hash, collisions appear after ~264 attempts — far too few for security. This is exactly why MD5 (128-bit output) was broken.
SHA-256: How It Works (Simplified)
SHA-256 follows the Merkle-Damgård construction: pad the message, split it into blocks, and process each block sequentially, updating a running state.
SHA-256 pipeline
1. Pad message to a multiple of 512 bits
(append a 1 bit, then zeros, then the 64-bit message length)
Split padded message into 512-bit blocks: B₁, B₂, ..., Bₙ
Initialize state: eight 32-bit words (H₀ through H₇)
derived from the square roots of the first 8 primes
For each block Bᵢ:
┌─────────────────────────────────────────────┐
│ Expand 512-bit block into 64 message words │
│ Run 64 rounds of mixing: │
│ - Bitwise ops: AND, OR, XOR, NOT │
│ - Bit rotations and shifts │
│ - Addition mod 2³² │
│ - A unique round constant (from cube │
│ roots of the first 64 primes) │
│ - One message word per round │
│ Add round result to running state │
└─────────────────────────────────────────────┘
Final state (H₀ || H₁ || ... || H₇) = 256-bit hash
Each block updates the running state. The final state is the hash. This is the Merkle-Damgård construction: each block "compresses" new data into a fixed-size state, chaining the output of one block into the input of the next.
Hash Functions Through History
| Algorithm | Output size | Status | Notes |
|---|---|---|---|
| MD5 | 128 bits | Broken | Collisions found in 2004; practical forgeries demonstrated |
| SHA-1 | 160 bits | Broken | Google produced a real-world collision in 2017 (SHAttered) |
| SHA-256 | 256 bits | Secure | Widely used; part of the SHA-2 family |
| SHA-3 / Keccak | 256 bits | Secure | Different construction (sponge) — not vulnerable to length extension |
| BLAKE2 / BLAKE3 | 256 bits | Secure | Very fast in software; BLAKE3 is parallelizable |
MD5 and SHA-1 should never be used for security purposes. They remain common in non-security contexts (checksums, cache keys) but any cryptographic use is dangerous.
MACs: Hash + Secret Key
A hash alone doesn't authenticate. Anyone can compute SHA-256 — including an attacker who modifies a message and recomputes the hash. To prove that a message came from someone who knows a secret, you need a MAC (Message Authentication Code). A MAC combines a hash with a secret key. Only someone who holds the key can produce or verify the tag.
The standard construction is HMAC (Hash-based MAC), defined as:
HMAC construction
HMAC(K, m) = H( (K ⊕ opad) || H( (K ⊕ ipad) || m ) )
Where:
K = secret key (padded to block size)
opad = 0x5c repeated to fill one block
ipad = 0x36 repeated to fill one block
H = hash function (e.g., SHA-256)
|| = concatenation
⊕ = XOR
Step by step:
- XOR the key with ipad → inner key
- Hash(inner key || message) → inner hash
- XOR the key with opad → outer key
- Hash(outer key || inner hash) → final HMAC tag
The result is a fixed-size tag. The receiver, who also knows K, computes the same HMAC and checks that it matches. If even one bit of the message was altered, the tags will differ.
HMAC vs Naive Approaches
Why not just H(key || message)?
Length extension attacks. With Merkle-Damgård hashes (MD5, SHA-1, SHA-256), knowing H(key || msg) lets an attacker compute H(key || msg || padding || extension) without knowing the key. The attacker simply takes the hash output as the internal state and continues hashing. HMAC's nested construction — hashing the result a second time with a different key derivation — prevents this entirely.
Naive: H(key || msg)
Vulnerable to length extension. An attacker who sees the hash can append data and compute a valid hash for the extended message without the key.
HMAC: H(K⊕opad || H(K⊕ipad || msg))
The outer hash makes length extension useless. Even if you extend the inner hash, the outer hash produces a completely different result. Provably secure.
Real-World Applications
Hash functions and MACs appear everywhere in modern systems:
- Password storage — store the hash of a password, never the plaintext. When a user logs in, hash their input and compare. (In practice, use a proper KDF like bcrypt, scrypt, or Argon2 — plain hashing is too fast for passwords.)
- File integrity — publish a SHA-256 checksum alongside a download. Users hash the downloaded file and compare to detect corruption or tampering.
- Digital signatures — sign the hash of a document, not the document itself. RSA and ECDSA operate on small inputs, so you hash first, then sign the digest.
- TLS record integrity — every TLS packet carries an HMAC (or AEAD tag) so the receiver can detect any modification in transit.
- Git — every commit, tree, and blob is identified by its SHA-1 hash. Git is content-addressed storage: the hash is the identifier. (Git is migrating to SHA-256.)
- Blockchain — each block contains the SHA-256 hash of the previous block, forming a tamper-evident chain. Changing any block invalidates every subsequent hash.
Where You'll Find Hashing and MACs
| System | Hash / MAC usage |
|---|---|
| TLS 1.3 | HMAC-SHA-256 in HKDF for key derivation; AEAD tags for integrity |
| SSH | HMAC on every packet; host key fingerprints are hashes |
| Git | SHA-1 (moving to SHA-256) for content-addressed object storage |
| Bitcoin | Double SHA-256 for block hashing; RIPEMD-160 for addresses |
| Password databases | bcrypt / Argon2 (slow hashes) to store credentials |
| Software distribution | SHA-256 checksums for package integrity (apt, pip, npm) |
| JWT (JSON Web Tokens) | HMAC-SHA-256 to authenticate token claims |
| API authentication | HMAC signatures on requests (AWS Signature V4) |
Hash vs. MAC at a glance
Hash (no key — anyone can compute):
Message ──→ [ SHA-256 ] ──→ Digest
│
Verifier recomputes and compares
MAC (requires shared secret key):
Message ─┬──→ [ HMAC-SHA-256 ] ──→ Tag
│ ↑
│ Key (shared)
│
└── Only key holders can produce or verify the tag
Try It Yourself — Live SHA-256
Type anything and watch the SHA-256 hash update in real time. Change a single character to see the avalanche effect — every bit of the hash changes unpredictably.
Birthday Paradox Simulator
See how quickly collisions appear with a small hash. Choose a hash size and run the simulation — the smaller the hash, the fewer attempts needed. This is why cryptographic hashes need large outputs (256+ bits).
HMAC Construction Visualizer
Enter a message and a secret key to see HMAC-SHA-256 computed step by step. The nested hash construction prevents length extension attacks and ensures only key holders can produce valid tags.
Key Takeaways
- A hash function maps arbitrary input to a fixed-size digest — deterministic, fast, and one-way
- Cryptographic hashes must resist preimages, second preimages, and collisions
- The birthday paradox means collision resistance is only half the output length: SHA-256 gives 128-bit collision security
- MD5 and SHA-1 are broken — use SHA-256, SHA-3, or BLAKE2/BLAKE3
- A hash alone doesn't authenticate; a MAC (like HMAC) adds a secret key to prove origin
- Never use H(key || msg) — length extension attacks break it. HMAC's nested construction is the safe choice
- Hashing underpins passwords, file integrity, digital signatures, TLS, Git, and blockchains
Hashes give you integrity — confidence that data hasn't changed. MACs add authentication — proof that the data came from someone who holds the key. But MACs require a shared secret: both parties must know the key. What if you need to prove authorship to the world, not just to one other party? That's the domain of digital signatures, where asymmetric cryptography meets hashing to produce unforgeable, publicly verifiable proof of origin.