← Lessons

quiz vs the machine

Platinum1740

Security

Constant Time Comparison

How early exit comparisons leak secrets through timing and how to avoid it.

5 min read · advanced · beat Platinum to climb

A Subtle Side Channel

Comparing secrets seems trivial, but a naive comparison can leak them. A typical equality check stops at the first differing byte. That means a comparison that fails on the first byte returns slightly faster than one that fails on the tenth byte. An attacker who measures these tiny timing differences can recover a secret one byte at a time.

This is a timing side channel, and it threatens checks of MAC tags, password hashes, API keys, and session tokens.

Constant Time Comparison

The defense is a constant time comparison that always examines every byte and takes the same time regardless of where a mismatch occurs.

  • It accumulates differences across all bytes rather than returning early.
  • The timing reveals nothing about how many leading bytes matched.
  • Use the library provided constant time function rather than writing your own.

Apply it whenever you compare a user supplied value against a secret, especially authentication tags and tokens.

Key idea

Naive equality checks leak secrets through timing by exiting at the first mismatch, so compare secret values with a constant time function that always scans every byte and reveals nothing about partial matches.

Check yourself

Answer to earn rating on the learn ladder.

1. Why can a naive equality check leak a secret?

2. What does a constant time comparison guarantee?

3. Where should constant time comparison be applied?