TExcelTAD

HMAC and Timing-Safe Comparison

Webhooks from payment providers, AWS request signatures (SigV4), JWTs with HS256, TOTP codes in authenticator apps, signed cookies in web frameworks, the TLS 1.3 key schedule: all of them use HMAC, the hash-based message authentication code. HMAC turns any hash function into a MAC that is secure even when the hash has weaknesses such as length extension. Using it correctly comes down to three things: a real random key, the right input, and a comparison that doesn't leak time.

What a MAC is

A message authentication code takes a secret key and a message and produces a tag: tag = MAC(K, m). Without the key, an attacker who has seen any number of (message, tag) pairs must not be able to produce a valid tag for a new message. Sender and receiver share the key, so a MAC gives integrity and authenticity between them, but not non-repudiation (either could have made the tag).

How HMAC is built

HMAC (RFC 2104, FIPS 198-1) hashes twice with two derived keys:

text
HMAC(K, m) = H( (K' XOR opad) || H( (K' XOR ipad) || m ) )
K'   = K padded with zeros to the hash's block size (64 bytes for SHA-256); hashed first if longer
ipad = 0x36 repeated, opad = 0x5c repeated

The outer hash takes the inner digest as a short, fixed-length input under a different key, so extending the inner hash gains nothing: the attacker would need the outer key to produce the final tag. HMAC's security proof (Bellare, Canetti, Krawczyk, 1996, refined in 2006) needs only that the compression function behaves like a pseudorandom function, a weaker assumption than collision resistance. That is why HMAC-SHA1 and even HMAC-MD5 are not broken in the way SHA-1 and MD5 are, although new designs use HMAC-SHA-256.

HMAC in Python, checked and compared

The first lines check the implementation against RFC 4231 test case 1. The second part shows why comparing tags with == is a problem: a byte-by-byte comparison stops at the first difference, so the time it takes reveals how many leading bytes of a guess are right.

python · try it yourself
import hmac, hashlib
# RFC 4231 test case 1
key = b"\x0b" * 20
tag = hmac.new(key, b"Hi There", hashlib.sha256).hexdigest()
print(tag)
print(tag == "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7")

def naive_equal(a, b):                 # returns at the first difference: time leaks the prefix length
    steps = 0
    if len(a) != len(b): return False, steps
    for x, y in zip(a, b):
        steps += 1
        if x != y: return False, steps
    return True, steps
real = bytes.fromhex(tag)
for guess_prefix in (0, 1, 2, 8):
    guess = real[:guess_prefix] + bytes(32 - guess_prefix)
    print(f"guess with {guess_prefix} correct bytes: naive compare does {naive_equal(real, guess)[1]} steps,"
          f" compare_digest -> {hmac.compare_digest(real, guess)}")
b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7
True
guess with 0 correct bytes: naive compare does 1 steps, compare_digest -> False
guess with 1 correct bytes: naive compare does 2 steps, compare_digest -> False
guess with 2 correct bytes: naive compare does 3 steps, compare_digest -> False
guess with 8 correct bytes: naive compare does 9 steps, compare_digest -> False

The step count grows with the number of correct leading bytes; in a real program that count is a time difference. An attacker who can submit tags and measure response times guesses the first byte (256 tries, keep the slowest), then the second, and so on: about 256 × 32 = 8,192 guesses instead of 2^256. Network noise makes each measurement fuzzy, but statistics over many repetitions recover differences of nanoseconds to microseconds; Nate Lawson and Taylor Nelson showed in 2010 that such timing differences can be measured over networks and reported the same early-exit comparison in OAuth and OpenID libraries; earlier versions of several web frameworks and the Xbox 360's boot loader had exactly this bug too.

hmac.compare_digest compares in time that depends only on the length, not on where the first difference is. Python's == on bytes and strings is not guaranteed to do that.

Using HMAC correctly

  • Key: at least 32 random bytes from secrets.token_bytes(32), stored as a secret (Secrets policy), one key per purpose. A password is not a key; derive one with a KDF if you must start from a password.
  • Input: authenticate exactly the bytes you will act on. For webhooks that means the raw request body (before JSON parsing and re-serialisation) plus a timestamp, so old messages can't be replayed: providers typically sign timestamp + "." + body and reject timestamps older than a few minutes.
  • Output: compare with hmac.compare_digest; keep the full 32-byte tag (truncation to 16 bytes is acceptable for many protocols, but never below what the standard allows).
  • Encoding: compare bytes to bytes, or hex to hex in the same case; decoding errors must fail closed.

A webhook check in a dozen lines:

text
expected = hmac.new(KEY, timestamp + b"." + raw_body, "sha256").hexdigest()
if abs(now - int(timestamp)) > 300: reject("stale")
if not hmac.compare_digest(expected, header_signature): reject("bad signature")

How MAC problems are detected

  • Code review: ==, !=, .equals(), strcmp, memcmp or Arrays.equals on tags, signatures, tokens or password hashes; hash(key + data) instead of HMAC; MAC over parsed-then-reserialised data; missing timestamp or nonce (replay); weak keys such as "secret" or the app name.
  • Static analysis: Bandit, Semgrep and CodeQL have rules for non-constant-time comparisons of secrets and for hard-coded keys.
  • Secret scanning: HMAC keys committed to repositories (gitleaks, GitHub secret scanning).
  • Logs: many signature failures from one source can indicate guessing or a replay campaign.

How it is fixed

  • hmac.new(key, data, "sha256") with a random 32-byte key; hmac.compare_digest for every check (crypto.timingSafeEqual in Node, MessageDigest.isEqual in Java, subtle.ConstantTimeCompare in Go, CRYPTO_memcmp in OpenSSL).
  • Sign the raw bytes plus a timestamp, and enforce a freshness window.
  • Rotate keys with an id in the message so old and new keys can overlap during the change.

Pitfalls

  • Comparing hex digests where one side is upper-case: the check fails for honest messages, and someone "fixes" it by lower-casing only one side in a non-constant-time way.
  • Using the same key for HMAC and encryption: derive separate keys with HKDF.
  • Returning early on a length mismatch is fine (lengths are public); returning early on content is not.

Practice

1. A webhook handler parses the JSON body, re-serialises it with sorted keys and computes HMAC over the result. What can go wrong?

The sender signed its own serialisation, so honest messages may fail. Worse, two different raw bodies can parse to the same object (duplicate keys, Unicode escapes), so the check doesn't authenticate what was actually received. Sign and verify the raw bytes.

2. Why doesn't HMAC-SHA-256 suffer from length extension although SHA-256 does?

The final tag is an outer hash under a separate key of the inner digest; extending the inner computation gives a value the attacker can't turn into a valid outer hash without the key.

3. Rewrite if request.headers["X-Sig"] == expected: safely.

if hmac.compare_digest(request.headers.get("X-Sig", ""), expected):, with expected computed as a hex string of the same case (or compare decoded bytes), and a freshness check on a signed timestamp.

Test yourself

Why does HMAC hash twice with two derived keys?

  1. For speed
  2. So that length extension of the inner hash doesn't give a valid tag
  3. To make the tag longer
  4. Because SHA-256 needs two passes

What does hmac.compare_digest protect against?

  1. Hash collisions
  2. Timing attacks that reveal how many leading bytes of a guess are correct
  3. Replay attacks
  4. Weak keys

Which property does a MAC NOT provide?

  1. Integrity
  2. Authenticity between the key holders
  3. Non-repudiation
  4. Detection of tampering

What should a webhook receiver authenticate?

  1. The parsed JSON object
  2. The raw request body plus a signed timestamp
  3. Only the URL
  4. The sender's IP address