Security

What Is HMAC? Hash-Based Message Authentication Explained

11 min read
By
What Is HMAC? Hash-Based Message Authentication Explained

NovelCrypt

A hash function tells you that data has not changed. It cannot tell you who produced the data — because anyone can compute a hash. That single gap is the source of an enormous class of real attacks: forged webhook calls that trick servers into processing fake payment events, tampered API requests, minted session tokens.

HMAC closes the gap. It is one of the oldest and most widely deployed constructions in cryptography, hiding inside systems you use daily: Stripe webhooks, AWS API signatures, JWT tokens, TLS. And it does its job with nothing exotic — just a standard hash function and a shared secret key, combined in a construction that is more subtle than it looks.

The Problem: Hashes Prove Integrity, Not Origin

Suppose an API accepts requests and verifies each one by checking that SHA256(body) matches a hash sent alongside. An attacker who wants to submit a forged request simply computes SHA256(forged_body) themselves and attaches it. The check passes. The hash proved the body was not corrupted in transit — but the attacker is the one who produced both the body and the hash, so "uncorrupted" means nothing.

The missing ingredient is a secret. If producing the tag required knowledge that only the legitimate sender and receiver hold, then a valid tag would prove something the attacker cannot fake: origin. That is the idea behind a message authentication code, and HMAC is its dominant construction.

How HMAC Works

HMAC takes two inputs: a message and a secret key. It produces a fixed-size tag, typically 256 or 512 bits. The construction looks like this, conceptually:

HMAC(key, message) = H( (key XOR opad) || H( (key XOR ipad) || message ) )

where ipad and opad are fixed padding constants. Read it from the inside out: the key is mixed with an inner pad and hashed; that result is combined with the message and hashed again; finally the key is mixed with an outer pad and hashed with everything. Two hash passes, each salted with a differently-padded key.

Why two passes, and why the pads? Because the naive alternatives fail. Simply hashing key-then-message is vulnerable to length-extension attacks: with SHA-256's Merkle-Damgård structure, someone who sees H(key || message) can compute H(key || message || anything) without knowing the key — appending to an existing valid tag. Hashing message-then-key suffers from different collision-based forgeries. HMAC's nested design was published in 1996 and proven secure against both classes, which is why the extra hash pass and the odd-looking pads are not optional decoration — they are the security argument. When we say "do not roll your own MAC," this is the reason: the secure version and the broken version differ by one hash pass.

HMAC vs Hash vs Digital Signature

Three tools prove things about data, and confusing them causes design errors.

A plain hash proves integrity to anyone — no key, no origin. An HMAC proves integrity and origin to anyone holding the shared key — symmetric trust: both parties can produce valid tags, so neither can prove to a third party that the other sent a message. A digital signature proves origin to anyone, using asymmetric keys — only the private key holder can sign, so signatures provide non-repudiation that HMAC cannot.

Pick by trust model. Two servers sharing an API secret: HMAC, fast and symmetric. A document that must convince a court: signature. A file-integrity check for downloads: plain hash, possibly published alongside the file.

Where You Meet HMAC Every Day

Webhook verification is the canonical example. When Stripe sends your server a payment event, it includes an HMAC-SHA256 tag computed with a secret you both hold. Your server recomputes the tag from the raw body and rejects the request if it does not match — so a forged event, even one carrying a plausible-looking payload, fails verification because the forger lacks the secret. GitHub, Slack, Shopify, and most major APIs work identically. Our Stripe webhook HMAC verification guide walks the implementation.

JWT tokens signed with HS256 are HMAC-SHA256 tags over the token header and payload: the holder of the server secret can mint tokens; everyone else can read the payload (it is merely Base64-encoded, not encrypted) but cannot alter it without invalidating the tag. AWS Signature Version 4 authenticates every API call with a chain of HMAC computations. And in TLS, MAC-style integrity checks protect records — modern versions fold this into AEAD modes like AES-GCM, which combine encryption and authentication in one operation.

Implementation Rules That Actually Matter

Using HMAC correctly involves a short list of rules, each earned by a real class of past vulnerabilities.

Compare tags in constant time. A standard string comparison exits at the first differing byte, leaking how many bytes matched — an attacker can exploit that timing to forge a tag one byte at a time. Use a constant-time comparison; our timing-attack guide explains the mechanics.

Verify before parsing. In webhook handling, compute the HMAC over the raw request body before your framework parses it — JSON parsing can reorder or reformat, breaking the tag. Include a timestamp in the signed payload and reject old messages, defeating replay attacks where an attacker re-sends a captured valid message. And use a modern hash — HMAC-SHA256 is the default; HMAC-SHA512 where longer tags suit; HMAC-MD5, while structurally not broken, is deprecated and signals carelessness.

Key handling, finally, is ordinary secret hygiene: generate keys with a cryptographically secure random generator, store them outside code, rotate on schedule. Our CSPRNG guide covers proper generation.

Try It Yourself

The NovelCrypt HMAC generator lets you compute HMAC tags in your browser. Generate a tag for a message, then change one character of the message and regenerate — the tag changes completely. Then change one character of the key and regenerate — again, a completely different tag. That total dependence on the key is what makes forgery impossible without the secret, and it is why the same message authenticated by two different parties produces two unrelated tags.

The Bottom Line

HMAC is the standard construction for proving that a message is authentic and untampered, using a hash function and a shared secret. Its nested double-hash design exists because naive keyed hashes fall to extension and collision attacks — the construction is the security. It is symmetric: both key holders can produce tags, which makes it perfect for server-to-server authentication like webhooks and API signing, and wrong for non-repudiation, which needs digital signatures. When a system says "we verify the signature of every webhook" or "this token is signed," HMAC is very likely the machinery underneath — one of cryptography's quietest, most load-bearing inventions.

Frequently Asked Questions

What is HMAC in simple terms?

HMAC (hash-based message authentication code) is a way to prove that a message came from someone holding a shared secret key and was not modified on the way. The sender computes a keyed hash of the message; the receiver recomputes it with the same key. If the values match, the message is both authentic and intact. Without the key, an attacker cannot forge a valid tag for any message, even one they have seen.

Why not just hash the message together with the key?

Naive combinations like SHA256(key || message) or SHA256(message || key) are both vulnerable to extension and collision tricks that allow forgery. HMAC's nested construction — hash the key into an inner pad, hash that with the message, hash again with an outer pad — was proven secure against these attacks. This is exactly why you should never build your own keyed hash: the naive version looks fine and fails in ways that are hard to spot.

What is the difference between HMAC and a plain hash?

A plain hash like SHA-256 has no key: anyone can compute it, so it proves integrity but not origin — anyone could have produced the hash. HMAC adds a secret key, so only key holders can produce a valid tag. That is the difference between "the data was not corrupted" and "the data came from someone who knows the secret." Our HMAC vs hash guide covers the distinction in depth.

Where does HMAC appear in real systems?

Everywhere: Stripe, GitHub, and Slack sign their webhooks with HMAC so servers can reject forged events. JWTs use HMAC-SHA256 in the HS256 signing algorithm. TLS uses HMAC (in older versions) and AEAD modes derived from it for record integrity. AWS request signing (SigV4) authenticates API calls with HMAC. If a system verifies that a request is authentic using a shared secret, HMAC is almost certainly underneath.

Explore the Share Password Securely: Try it now

Try NovelCrypt Tools

Experience military-grade encryption for your sensitive data. Create self-destructing messages, encrypt files, or explore our experimental lab tools.

Explore NovelCrypt