Sub topic 14
Authenticating messages with HMAC
This chapter assumes you have read the earlier chapters on cryptographic properties and SHA-256 integrity checks. You should also be comfortable with Python bytes, XOR, and the idea of a secret key. By the end you will know why a plain hash cannot authenticate a message, how HMAC is built, and how to use it safely.
The problem: a hash proves nothing about who wrote the message
A SHA-256 digest is a fingerprint that anyone can compute. If you send a message together with its SHA-256 digest, an attacker who can change the message can also recompute the digest. The receiver sees a matching pair and has no reason to doubt it.
Integrity checks like the ones in the previous chapter only help when the digest travels over a channel the attacker cannot touch. An example is a checksum published on a trusted site while the file comes from a mirror. When both the message and the tag cross the same untrusted channel, you need a value only the legitimate parties can produce.
A message authentication code (MAC) is that value. It is a short tag computed from the message and a shared secret key. The receiver recomputes the tag with the same key and compares. A MAC gives you two guarantees:
- Integrity: the message was not changed after tagging.
- Authenticity: the tag came from someone who holds the key.
A MAC does not hide the message. The message stays in plain text unless you also encrypt it.
Why not just hash the key and the message together?
The obvious idea is SHA-256(key + message). With SHA-256 this is unsafe because of length extension.
SHA-256 belongs to the Merkle–Damgård family. It processes input in blocks and carries an internal state from one block to the next. The final digest is that internal state. So if an attacker knows SHA-256(key + message) and the length of key + message, they can load the digest back in as the state. They can then keep hashing and produce a valid digest for key + message + padding + suffix. They never learn the key.
Suppose a server signs user=bob and the attacker appends &admin=true. The attacker can compute a valid tag for the longer message without knowing the key. Other orderings fail too. SHA-256(message + key) is weaker against collisions, because a collision in the hash of the message alone carries over to any key.
Some hashes resist length extension by design, including SHA-3, BLAKE2, and truncated variants such as SHA-512/256. HMAC works with any hash and does not depend on that luck.
How HMAC is built
HMAC applies the hash twice, with the key mixed in at both layers. For a hash H with block size B (64 bytes for SHA-256):
- If the key is longer than
Bbytes, replace it withH(key). - Pad the key with zero bytes to exactly
Bbytes. Call the resultK'. - Compute the inner hash:
H((K' XOR ipad) || message), whereipadis the byte0x36repeatedBtimes. - Compute the outer hash:
H((K' XOR opad) || inner), whereopadis the byte0x5CrepeatedBtimes.
The outer hash is the tag. Because the attacker never sees the inner digest on its own, they have no state to extend. The result is a function of both key and message that does not leak the intermediate state.
You will almost never write this yourself, but doing it once shows there is no magic. This implementation matches the standard library:
import hashlib
import hmac
def my_hmac_sha256(key: bytes, msg: bytes) -> bytes:
block = 64 # SHA-256 block size in bytes
if len(key) > block:
key = hashlib.sha256(key).digest()
key = key.ljust(block, b"\x00")
ipad = bytes(b ^ 0x36 for b in key)
opad = bytes(b ^ 0x5C for b in key)
inner = hashlib.sha256(ipad + msg).digest()
return hashlib.sha256(opad + inner).digest()
key = b"k" * 20
msg = b"amount=100&to=alice"
print(my_hmac_sha256(key, msg) == hmac.new(key, msg, hashlib.sha256).digest())The program prints True. In real code, use hmac from the standard library and never your own version.
Signing and verifying in practice
A MAC has two operations. The sender computes a tag, and the receiver recomputes it and compares. The comparison must be constant-time.
import hashlib
import hmac
import os
key = os.urandom(32) # shared secret, 256 random bits
def sign(message: bytes) -> bytes:
return hmac.new(key, message, hashlib.sha256).digest()
def verify(message: bytes, tag: bytes) -> bool:
expected = sign(message)
return hmac.compare_digest(tag, expected)
msg = b"amount=100&to=alice"
tag = sign(msg)
print(verify(msg, tag)) # True
print(verify(b"amount=900&to=alice", tag)) # False
print(verify(msg, bytes(len(tag)))) # False: forged tagChanging one byte of the message produces a completely different tag, because the avalanche effect of the underlying hash carries through. The attacker can only guess a tag, and a correct guess has probability 2^-256.
Why compare_digest matters
A normal == on byte strings stops at the first byte that differs. An attacker who can submit many forged tags and measure response time can learn how many leading bytes were right. They can then recover a valid tag one byte at a time. This is a timing attack. hmac.compare_digest takes the same time wherever the difference lies.
Choosing keys, hashes, and tag lengths
- Key: generate it with a secure random source such as
os.urandomor thesecretsmodule. A key of at least the hash output size (32 bytes for SHA-256) is a good default. Do not use a human-chosen password as an HMAC key. If you must derive a key from a password, use a password hashing function from the previous chapter. - Hash: HMAC-SHA-256 is the common default. HMAC-MD5 and HMAC-SHA-1 are not broken by known collision attacks, because HMAC does not rely on collision resistance in the same way. Even so, avoid them in new designs, since there is no benefit and they invite audit questions.
- Tag length: you may truncate a tag to save space. RFC 2104 advises keeping at least half the hash output length and no fewer than 80 bits. Sixteen bytes is a common choice for SHA-256.
- Key reuse: use separate keys for separate purposes. A key that signs cookies should not also sign API requests.
Common errors
| Mistake | What goes wrong | Fix |
|---|---|---|
| `sha256(key + msg)` as the "MAC" | Length extension lets an attacker append data and forge a tag | Use `hmac.new` |
| Comparing tags with `==` | Timing differences leak correct prefix bytes | Use `hmac.compare_digest` |
| Concatenating fields without delimiters | `("ab", "c")` and `("a", "bc")` produce the same bytes and the same tag | Length-prefix or use an unambiguous encoding such as JSON with sorted keys |
| No nonce or timestamp | An attacker replays a valid message and tag later | Include a timestamp or counter inside the signed data and check it |
| Weak or hard-coded key | Anyone who reads the source can forge tags | Load a random key from the environment or a secrets store |
| Using HMAC for password storage | HMAC is fast, so guessing is cheap | Use scrypt, Argon2, or bcrypt with a salt |
The field ambiguity problem is easy to miss. The MAC covers exactly the bytes you feed it. If your format lets two different logical messages produce identical bytes, the tag cannot tell them apart.
Replay is a separate issue. A MAC proves a message was created by a key holder. It does not prove that it was created recently or that it was not sent before. Put freshness data inside the signed bytes.
Where HMAC fits in the larger picture
HMAC is the right tool when both parties already share a secret and need to detect tampering. Typical uses are signing webhook payloads, session cookies, and API request signatures, and as a building block inside key derivation functions such as HKDF.
It is not the right tool when the verifier must not be able to forge tags. Anyone who can verify an HMAC holds the key and can therefore also create valid tags. If you need many verifiers who cannot sign, you need digital signatures, which use a key pair. That topic is outside this chapter.
Exercise
A service signs each request with the tag SHA-256(secret + body) and sends both to a partner. Name two separate weaknesses in this design and give one fix for each.
Show answer
First, SHA-256 is vulnerable to length extension. An attacker who sees a body and its tag can append data and compute a valid tag for the longer body without knowing the secret. Fix: use HMAC-SHA-256 (hmac.new(secret, body, hashlib.sha256)). Second, if the partner checks the tag with ==, response timing can leak how many leading bytes of a guessed tag are correct. Fix: compare with hmac.compare_digest. (Also acceptable: the signed data has no timestamp or nonce, so a captured request can be replayed. Fix: include a timestamp in the signed bytes and reject old ones.)
Exercise
Why does my_hmac_sha256 hash the key first when it is longer than 64 bytes, and what happens to a key shorter than 64 bytes?
Show answer
The construction XORs the key with pads that are exactly one block (64 bytes) long, so the key must fit in one block. A longer key is first shortened by hashing it with SHA-256 to 32 bytes. A shorter key is padded with zero bytes up to 64 bytes. In both cases the result K' is exactly one block long.