What is HMAC?
HMAC (Hash-based Message Authentication Code) is a type of message authentication code that combines a cryptographic hash function with a secret key. It provides both data integrity (the message was not altered) and authentication (the sender knows the secret key). HMAC is defined in RFC 2104 and is widely used in API authentication, JWT signing, and webhook verification.
A plain hash function (e.g., SHA-256) verifies data integrity but not authenticity — anyone can compute a hash. HMAC adds a secret key to the computation so that only parties who know the key can produce or verify the correct MAC. The algorithm pads the key to the hash block size, XORs it with inner and outer padding constants, and runs two nested hash operations: H(K ⊕ opad || H(K ⊕ ipad || message)).
This two-pass construction prevents length extension attacks that affect plain hash constructions like H(key || message). HMAC is provably secure as long as the underlying hash function is collision-resistant and the key is secret.
HMAC-SHA256 is the most common variant. It is used in JWT signing (the HS256 algorithm), AWS request signing (Signature Version 4), OAuth 1.0 signature generation, TOTP/HOTP one-time password algorithms (RFC 6238 / RFC 4226), TLS 1.2 PRF, and webhook payload verification (GitHub, Stripe, and most SaaS providers send an HMAC-SHA256 signature with each webhook so you can verify the payload came from them).
To verify an HMAC, the recipient recomputes it using the same key and compares to the value in the request. Comparison should be done in constant time to prevent timing attacks — most languages provide a dedicated function for this (e.g., `crypto.timingSafeEqual` in Node.js, `hmac.compare_digest` in Python).
HMAC does not encrypt — the payload is still visible. For confidentiality, use HMAC alongside encryption or use an authenticated encryption scheme (AES-GCM).