What Is an HMAC and When Do You Need One?
An HMAC (Hash-based Message Authentication Code) is a hash computed using a secret key. A regular hash tells you the fingerprint of some data. An HMAC tells you the fingerprint of some data as produced by someone who knows the secret key. That distinction is the entire point.
Regular hash vs HMAC
A regular hash (SHA-256, MD5) takes data and produces a fixed-size fingerprint. Anyone can compute it — there's no secret involved. If I send you {"amount": 100} with its SHA-256 hash, an attacker who intercepts the message can modify it to {"amount": 1000}, recompute the SHA-256, and send you the modified message with a valid new hash. You'd have no way to know it was tampered with.
An HMAC uses a shared secret key in addition to the data. The HMAC of {"amount": 100} using key secret123 can only be computed by someone who knows secret123. An attacker who doesn't know the key can't produce a valid HMAC for a modified message. This provides integrity and authentication — you know the message came from someone who knows the key and that it wasn't modified in transit.
HMAC-SHA256(key="secret", message="amount=100")
→ 7d0a89...
HMAC-SHA256(key="secret", message="amount=1000")
→ f3c451... # completely different — attacker can't produce this without the key
When you need HMAC
Webhook signatures. Services like Stripe, GitHub, and Slack sign webhook payloads with HMAC-SHA256 using a secret key they share with you. When you receive a webhook, you recompute the HMAC and compare it to the signature in the request header. If they match, the webhook came from the service and wasn't tampered with.
API request signing. AWS Signature Version 4, for example, uses HMAC-SHA256 to sign API requests. The signature proves the request came from someone with valid credentials and protects against replay attacks and tampering.
Stateless tokens. HMAC-based tokens like JWTs (using HS256) include a signature computed from the token contents and a secret. Anyone can read the token contents (they're base64-encoded, not encrypted), but the HMAC signature prevents modification without invalidating the token.
Which HMAC algorithm to use
Use HMAC-SHA256 for new systems. It's secure, widely supported, and fast enough for all practical use cases. HMAC-SHA512 provides a larger output but the security difference isn't meaningful for most applications. Avoid HMAC-MD5 and HMAC-SHA1 in new code — the underlying hash functions have weaknesses, though HMAC is somewhat more resistant to the known attacks than the plain hash functions.