HMAC vs. Plain Hashing: Why a Secret Key Changes Everything
Published 2026-09-14
The naive approach that seems secure but isn't
It might seem like you could build a secure message authentication code by just hashing a secret key concatenated with a message: hash(secret + message). This intuitive approach has a real, exploitable flaw called a length-extension attack, which affects hash functions built on the older Merkle-Damgård construction, including MD5 and SHA-256 used this naive way.
What a length-extension attack actually does
Because of how these hash functions process data internally in sequential blocks, an attacker who sees hash(secret + message) can, without ever knowing the secret itself, compute a valid hash for secret + message + (attacker's extra data) — effectively appending malicious content to a message and producing a hash that still looks legitimately signed with the secret. This is a genuinely dangerous, well-documented flaw in the naive approach, not a theoretical edge case.
How HMAC actually fixes it
HMAC (Hash-based Message Authentication Code) doesn't just concatenate the key and message once — it uses a specific two-layer construction, hashing the key and message together, then hashing that result again combined with the key a second time (using two different padded versions of the key, called the inner and outer pad). This nested structure is specifically designed to block length-extension attacks, which is the whole reason HMAC exists as a separate standard instead of everyone just hashing a key and message together directly.
Where HMAC is used in practice
- API request signing: many APIs require you to sign each request with an HMAC of the request data and a shared secret, so the server can confirm the request genuinely came from someone who holds that secret and wasn't tampered with in transit.
- Webhook verification: services like payment processors sign webhook payloads with HMAC so your server can verify a webhook actually came from them, not an attacker pretending to.
- JWT signing (HS256): when a JWT uses the HS256 algorithm, its signature is an HMAC using SHA-256 and a shared secret.
Generate one yourself
Our HMAC Generator computes a proper HMAC using your browser's native Web Crypto API across SHA-1, SHA-256, SHA-384 or SHA-512, entirely client-side.