Course contentsShow
← Security
Lesson 220 of 3,0525. Cryptographic Hashing and MACsFree lesson

Timing Attacks on MAC Verification

Learn how timing side-channels can leak information during MAC comparison and implement constant-time verification.

Timing Attacks on MAC Verification

You'll learn how tiny differences in comparison time can leak secret information and how to prevent this vulnerability.

The Problem with "Fast Fail" Comparisons

When verifying an HMAC (or any MAC), you compare the MAC you computed against the MAC provided by the sender. The naive approach is to compare byte-by-byte and exit immediately when you find a mismatch:

if computed_mac[0] != provided_mac[0]: return False
if computed_mac[1] != provided_mac[1]: return False
...

This leaks information through timing! If the first byte is wrong, the function returns instantly. If the first byte is correct but the second is wrong, it takes slightly longer. An attacker can measure these microsecond differences across thousands of attempts to guess the MAC byte-by-byte.

The Analogy

Imagine a password door that beeps once for each correct character before locking you out. You'd try "A..." (one beep), then "B..." (silence), then "C..." (one beep) — gradually discovering "CAT" character by character. That's a timing attack.

The Solution: Constant-Time Comparison

Always compare every byte, regardless of whether you've found a mismatch:

def constant_time_compare(a, b):
    if len(a) != len(b):
        return False
    
    result = 0
    for x, y in zip(a, b):
        result |= x ^ y  # accumulate differences
    
    return result == 0  # only check once at the end

This takes the same amount of time whether the MACs match perfectly or differ in the first byte. The attacker learns nothing from timing measurements.

Why This Matters

Timing attacks are not theoretical — they've been used to break real systems over networks. Even small timing differences (nanoseconds) can be amplified through statistical analysis.

Key Takeaway: Always use constant-time comparison functions for MAC verification; byte-by-byte early-exit comparisons leak information through timing side-channels that attackers can exploit to forge valid MACs.