HMAC-SHA256 Authentication
Learn how HMAC-SHA256 works for message authentication. Covers the keyed hashing construction, API signature use cases, and implementation best practices.
Detailed Explanation
HMAC-SHA256 (Hash-based Message Authentication Code with SHA-256) is a construction that combines a secret key with the SHA-256 hash function to produce an authentication tag. It verifies both the integrity and authenticity of a message, confirming that the data has not been altered and that it originated from someone possessing the secret key.
How HMAC works:
HMAC uses a two-pass hashing scheme defined in RFC 2104. Given a secret key K and message M, the computation is: HMAC(K, M) = SHA-256((K' XOR opad) || SHA-256((K' XOR ipad) || M)), where K' is the key padded to the block size (512 bits for SHA-256), ipad is 0x36 repeated, and opad is 0x5c repeated. The inner hash processes the key XORed with ipad concatenated with the message. The outer hash processes the key XORed with opad concatenated with the inner hash result.
Why not just hash the key with the message?
A naive approach like SHA-256(key + message) is vulnerable to length-extension attacks. Because SHA-256 uses Merkle-Damgard construction, an attacker who knows SHA-256(key + message) can compute SHA-256(key + message + padding + extension) without knowing the key. HMAC's nested hashing construction eliminates this vulnerability entirely.
Common applications:
HMAC-SHA256 is used extensively in API authentication. AWS Signature Version 4 uses HMAC-SHA256 to sign API requests. JWT (JSON Web Tokens) commonly use HS256 (HMAC-SHA256) for token signatures. Webhook verification systems (GitHub, Stripe, Slack) use HMAC-SHA256 to authenticate payloads. OAuth 1.0 also relies on HMAC for request signing.
Implementation guidance:
Use your language's standard cryptographic library for HMAC (e.g., Node.js crypto.createHmac, Python hmac module, Java javax.crypto.Mac). Never implement HMAC yourself. Use constant-time comparison when verifying HMAC tags to prevent timing attacks. Keys should be at least 256 bits (32 bytes) of cryptographically random data. Rotate keys periodically and have a key versioning scheme.
Use Case
HMAC-SHA256 is the standard mechanism for signing API requests (AWS, Stripe, GitHub webhooks) and for generating JWT tokens using the HS256 algorithm.