HMAC (Hash-based Message Authentication Code) is a specific construction for creating a message authentication code using a cryptographic hash function combined with a secret key. It provides two guarantees: the message has not been altered in transit (integrity), and it was created by someone who possesses the secret key (authenticity). HMAC is widely used in API authentication, token verification, and secure communication protocols.
How It Works
HMAC combines a hash function (like SHA-256) with a secret key through a specific algorithm defined in RFC 2104. The sender computes HMAC(key, message) and sends both the message and the resulting MAC. The receiver, who also knows the secret key, computes the HMAC independently and compares it to the received value. If they match, the message is authentic and unmodified.
Unlike a plain hash, HMAC cannot be forged without knowing the secret key. If an attacker intercepts a message and its SHA-256 hash, they can modify the message and compute a new valid hash. With HMAC, modifying the message requires recomputing the MAC with the secret key, which the attacker does not possess.
In web applications, HMAC appears in several contexts. Webhook signatures use HMAC to verify that incoming requests genuinely originate from the claimed service. API authentication schemes use HMAC to sign requests, proving the caller possesses the API secret without transmitting it. JWT tokens signed with HMAC (HS256) use the algorithm to ensure tokens have not been tampered with. Session tokens and CSRF tokens may use HMAC internally to bind them to specific users or sessions.
Why It Matters
HMAC implementation mistakes create serious vulnerabilities. Using a weak or predictable key defeats the purpose entirely. Comparing HMAC values with standard string comparison instead of constant-time comparison introduces timing attacks that allow an attacker to reconstruct the valid MAC byte by byte. Failing to validate HMAC signatures on incoming webhooks means the application trusts any request that looks like a webhook, enabling forgery.
Security assessments check that HMAC is used where message authenticity matters, that keys are sufficiently random and securely stored, and that comparison operations are timing-safe.
Need your application tested? Get in touch.