HMAC & Message Authentication
Cryptographic Protocols · Networking & Cryptography track
8 min read
In this module
Proving the Message Is Genuine
Encryption hides data from eavesdroppers. But what about attackers who modify the encrypted data in transit? If you receive an encrypted message, how do you know it hasn't been tampered with? This is the problem of message authentication, and HMAC is one of the most important solutions.
The distinction between confidentiality and integrity is subtle but load-bearing. Encryption on its own doesn't guarantee integrity. A ciphertext can be flipped, truncated, or spliced together with another ciphertext, and the recipient has no way to spot the change without an additional integrity mechanism. Message authentication codes are that mechanism.
Message Authentication Codes
A Message Authentication Code (MAC) is a short piece of data that accompanies a message, allowing the recipient to verify both:
- Integrity: The message has not been modified
- Authenticity: The message came from someone who knows the secret key
A MAC is like a digital signature, only symmetric. Sender and receiver share the same secret key. That means MACs can't deliver non-repudiation (either party could have generated the tag), but they're far faster to compute than asymmetric signatures.
HMAC: Hash-Based MAC
HMAC (Hash-based Message Authentication Code) constructs a MAC from a cryptographic hash function and a secret key. The construction is:
HMAC(key, message) = hash((key XOR opad) || hash((key XOR ipad) || message))Where:
ipadis the byte 0x36 repeated to fill a blockopadis the byte 0x5c repeated to fill a block||means concatenation
This double-hashing construction was carefully designed to defeat length-extension attacks and other weaknesses that haunt simpler constructions like hash(key || message). The choice of 0x36 and 0x5c keeps the inner and outer keys sufficiently different so the two hash invocations don't interact in exploitable ways.
HMAC combines a hash function with a secret key using a specific construction that prevents known attacks. HMAC-SHA256 is the most common variant. Unlike a plain hash (which anyone can compute), only someone who knows the key can generate or verify an HMAC tag. This is what transforms a hash function from a fingerprinting tool into an authentication mechanism.
Why Not Just Hash(key + message)?
You might assume hash(key || message) would do the job. It doesn't, thanks to length-extension attacks. For hash functions built on the Merkle-Damgard construction (SHA-256, SHA-512), knowing hash(data) lets you compute hash(data || extra_data) without knowing data.
It's a quirk of how those hash functions process data: the internal state after the last block is the output. An attacker who sees the hash output knows the internal state, and can pick up the computation from there with extra data. So they could take a valid MAC hash(key || message) and compute hash(key || message || attacker_data) without ever seeing the key.
HMAC kills this by wrapping the hash in a two-layer structure. The inner hash produces an intermediate value, and the outer hash processes that value under a differently-keyed state. An attacker trying to extend the outer hash can't predict the inner hash's contribution, and the attack falls apart.
Forge one yourself. The demo below takes a tag computed as SHA-256(key ‖ message), appends your text, and produces a valid tag for the longer message without ever seeing the key. The HMAC of the same forged message doesn't match.
Computing…
Why not SHA-256(key ‖ message)?
SHA-256 is a Merkle–Damgård hash: the digest is the whole internal state after the last block. Anyone holding that tag can load it back in and keep hashing. They don't need the key, only its length, which is easy to guess.
Naive tag: SHA-256(key ‖ message)
48fe08f4de824226da8232509c73640f02d4e8c40b1522f59e6c66c348e683ce
Forged message (key not included)
user=alice&role=reader\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00&role=admin
Original message, then the padding SHA-256 added after key ‖ message (32 bytes), then the appended text.
Forged tag, computed from the naive tag alone
2bb296fb7e58a38331626a2a376ff22395c086048bfd3a8b395916e7f147b93d
The server recomputes SHA-256(key ‖ forged message): it matches, so the forgery is accepted.
HMAC in Practice
HMAC is everywhere:
API authentication: Many APIs use HMAC to authenticate requests. The client signs the request parameters with a shared secret, and the server verifies the signature. The signature proves the request came from someone who knows the secret and arrived without modification.
// Typical API authenticationsignature = HMAC-SHA256(api_secret, "GET /api/data?user=alice×tamp=1234567")Request includes: Authorisation: HMAC signatureJWT (JSON Web Tokens): With the HS256 algorithm, JWTs are signed with HMAC-SHA256. The server can confirm a token was issued by itself and hasn't been altered. That's the backbone of stateless authentication in countless web applications. The classic JWT bugs come from trusting the token's own alg header: libraries that accepted "alg": "none" skipped verification entirely, and a server expecting RS256 could be tricked into checking an HS256 token using its public RSA key as the HMAC secret, which anyone can download. Pin the expected algorithm on the server instead of reading it from the token.
TLS record layer: Each encrypted record in TLS carries an authentication tag (in AEAD modes like GCM) or, in TLS 1.2 and earlier, a separate HMAC to verify integrity. TLS 1.3 allows AEAD only. Without that tag, an attacker on the network could silently modify encrypted traffic.
Cookie security: Frameworks sign session cookies with HMAC so clients can't forge or alter them. The server holds the HMAC key, and any cookie that arrives with an invalid tag gets thrown out.
Encrypt-then-MAC vs. MAC-then-Encrypt
The order matters:
Encrypt-then-MAC (correct): Encrypt the plaintext, then compute the MAC over the ciphertext. The receiver checks the MAC first and only decrypts if it's valid. The receiver never processes tampered ciphertext, which wipes out entire classes of attacks including padding oracle vulnerabilities.
MAC-then-Encrypt (risky): Compute the MAC over the plaintext, then encrypt both. The receiver has to decrypt before checking the MAC, which means processing potentially malicious ciphertext. This ordering enabled padding oracle attacks against TLS. An attacker could modify the ciphertext, force decryption, and learn information from the error behaviour, all because the MAC check happened too late.
Modern AEAD ciphers (AES-GCM, ChaCha20-Poly1305) bundle encryption and authentication into a single operation, dodging the ordering question entirely. That's the recommended approach for all new systems.
Constant-Time Comparison
When verifying an HMAC, you compare the computed tag against the received tag. A naive byte-by-byte comparison that returns early on the first mismatch leaks timing information. An attacker can figure out how many bytes matched just by measuring response time.
Constant-time comparison always compares all bytes regardless of whether a mismatch is found:
function constant_time_equal(a, b) { result = 0 for i = 0 to length(a) - 1 { result = result OR (a[i] XOR b[i]) } return result == 0}Same execution time regardless of where (or whether) the tags differ, which shuts the timing attack down. Every HMAC verification should use constant-time comparison. Most cryptographic libraries provide a dedicated function for this; use it instead of your language's default equality operator.
The program below plays the attack out. The server checks a forged transfer request with an early-exit comparison, and the attacker, who never sees the key, builds a valid tag one byte at a time by keeping whichever guess made the server do the most work. Real attacks measure response times and need many samples per guess; here a counter stands in for the clock. The MAC is a toy HMAC on a weak 64-bit hash, so don't reuse it.
A second bug: the client signs only "POST /transfer" and sends ?to=alice&amount=10 alongside. What can an attacker do?
Anything they like to the unsigned part. The tag still verifies after to=alice becomes to=mallory and 10 becomes 9999, because none of those bytes went into the HMAC. Sign everything the server acts on (method, path, query, body and a timestamp or nonce to stop replays) in one canonical byte string.