HMAC vs Plain Hashing: Length Extension Attacks
You'll learn why using a plain hash for message authentication is dangerously vulnerable and how HMAC solves this problem.
The Problem with Plain Hashing for Authentication
Imagine you want to authenticate a message by computing hash(secret || message) and sending both the message and hash. Seems secure, right? The attacker doesn't know your secret, so they can't forge the hash.
Wrong. Many hash functions like SHA-256 and SHA-512 are vulnerable to length extension attacks. An attacker who sees hash(secret || message) can compute hash(secret || message || attacker_data) without knowing the secret. They can append malicious data and produce a valid hash—breaking your authentication completely.
Why This Happens
Hash functions like SHA-2 process data in blocks and maintain an internal state. The final hash is that internal state. An attacker can use your hash as a starting point, continue the hashing process with new data, and produce a valid hash for the extended message.
Think of it like a relay race: the hash is like passing a baton. Even if you don't know what happened in earlier legs of the race, you can grab the baton and keep running.
How HMAC Prevents This
HMAC (Hash-based Message Authentication Code) uses a construction like hash(key ⊕ opad || hash(key ⊕ ipad || message)). This nested structure with key mixing means:
- The final hash doesn't directly expose the internal state of the message processing
- An attacker can't extend the computation without knowing the key
- Even length-extension-vulnerable hashes become secure
Key Takeaway: Never use plain hash(secret || message) for authentication—always use HMAC, which is specifically designed to prevent length extension attacks and provide secure message authentication.