HMAC, short for Hash-based Message Authentication Code, is a mechanism that combines a cryptographic hash function with a secret key to produce a code that verifies both the integrity and the authenticity of a message. Unlike a plain hash, which anyone can compute, an HMAC can only be generated or verified by parties that share the secret key, proving the message came from a legitimate sender and was not altered.
The construction wraps a hash function — such as SHA-256, yielding HMAC-SHA256 — around the message and a key using a specific, standardized scheme with inner and outer padding. This design protects against length-extension attacks that would affect naively concatenating a key and message with certain hash functions, making HMAC a robust and well-analyzed approach to message authentication.
HMAC is everywhere in secure communication. APIs use it to sign requests so the server can confirm the caller holds the shared secret and that parameters were not tampered with in transit. Webhooks include an HMAC signature so the receiver can verify the payload genuinely came from the sender. JSON Web Tokens signed with the HS256 algorithm rely on HMAC-SHA256 to guarantee the token was issued by a trusted party.
The security of HMAC depends entirely on keeping the key secret and comparing signatures safely. The shared key must never be exposed in client-side code or logs, and verification should use constant-time comparison to avoid timing attacks. When both sides guard the key properly, HMAC provides strong, efficient assurance that a message is authentic and unmodified.