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.