What HMAC solves
A hash like SHA-256 tells you whether two messages are identical, but not who generated them. Anyone can compute SHA-256 of a message, so it's useless for authenticating the source. HMAC fixes that by combining the message with a secret key in a specific way: only someone who knows the key can produce the correct HMAC.
It's standardized in RFC 2104 (1997) and built on top of any cryptographic hash. Common variants today are HMAC-SHA-256, HMAC-SHA-384 and HMAC-SHA-512. HMAC-SHA-1 still works but is no longer recommended for new builds.
How HMAC is constructed
Simplified: HMAC(K, m) = H((K' xor opad) || H((K' xor ipad) || m)), where:
H: the underlying hash function (SHA-256, SHA-512, etc.).K': the key normalized to the block size (zero-padded or hashed if too long).ipad,opad: specific constants (0x36 and 0x5C repeated).m: the message.
That double pass is what makes HMAC resistant to length-extension attacks that affect
naive schemes like H(K || m).
Typical use cases
- Webhook verification. Stripe, GitHub, Slack and others sign every webhook with HMAC. Your server recomputes with the shared secret and compares.
- API authentication. AWS Signature v4, for example, uses HMAC-SHA-256 to sign every request.
- Signed cookies. Frameworks like Express or Django sign cookies to detect tampering.
- Single-use tokens. A timestamped token can carry its HMAC to prevent forgery without a database table.
- JWT with HS256. Internally uses HMAC-SHA-256.
HMAC best practices
- Constant-time comparison. Use
crypto.timingSafeEqualin Node,hmac.compare_digestin Python. String-to-string comparison enables timing attacks. - Key of at least 256 bits. For HMAC-SHA-256, a random 32-byte key is recommended. For HMAC-SHA-512, 64 bytes.
- Don't reuse the key for other purposes. A key should serve a single role.
- Rotate keys. Like any secret, they should rotate periodically.
- Include a timestamp. To prevent replay attacks, sign body plus timestamp and reject old signatures.
HMAC vs asymmetric signatures
HMAC uses a shared key: both signer and verifier know it. That's simple and fast, but it means either party can produce valid signatures — you can't prove who signed.
Asymmetric signatures (RSA, ECDSA, EdDSA) use a private key to sign and a public key to verify. Only the private-key holder can sign, so you can attribute signatures. The downside: they're slower and the private key needs strong protection.
For webhooks between two parties that already trust each other, HMAC is ideal. For public distribution or auditability, prefer asymmetric signatures.
Privacy of this generator
Everything is computed with crypto.subtle.sign, the browser's native
implementation. Your message and key never leave your device. In production, you still
shouldn't trust the browser to compute HMAC: the secret has to live on the server.