Here is the side channel I promised. Compare an authentication tag, a token, or a password hash with memcmp and you have a timing leak:
// leaks: returns at the first mismatch
if (memcmp(received_tag, expected_tag, 32) == 0) { /* ok */ }
memcmp is allowed to stop at the first different byte, and usually does. So a tag that matches the first byte takes slightly longer to reject than one that does not. Over a quiet network that difference is tiny, but it is statistical: with enough samples the noise averages out. Researchers have shown this on local networks and on shared machines. In my own lab I can see it with two processes on the same board and a cycle counter.
The fix is to touch every byte, always, and combine the result without branching:
#include <stddef.h>
#include <stdint.h>
int ct_equal(const uint8_t *a, const uint8_t *b, size_t n) {
uint8_t diff = 0;
for (size_t i = 0; i < n; i++)
diff |= a[i] ^ b[i];
return diff == 0;
}
Three caveats that matter more than the snippet:
- "Constant time" is a property of the machine code, not your source. An optimising compiler is allowed to turn a clever loop back into an early exit. Do not hand-roll it in production.
- Use the library function:
CRYPTO_memcmp,sodium_memcmp,hmac.compare_digestin Python,crypto.timingSafeEqualin Node. They exist exactly for this and were reviewed by people who care. - The secret-dependent length also leaks. Compare fixed-size values (hash both sides first if you must compare variable-length input).
Being correct on paper was never the problem. The problem is the clock on the wall.