security
cryptography
ai_generated
true
Secret comparison vulnerable to timing attack because regular == leaks information via response time
ID: security/timing-attack-string-comparison
85%Fix Rate
88%Confidence
3Evidence
2023-01-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| any | active | — | — | — |
Root Cause
Regular string comparison (==) short-circuits on first different byte. By measuring response time, attackers can determine how many leading bytes match. For API keys, HMAC signatures, and tokens, this leaks the secret byte-by-byte.
genericWorkarounds
-
95% success Use hmac.compare_digest() for constant-time comparison in Python
import hmac; hmac.compare_digest(received_signature, computed_signature) # constant time
-
95% success Use crypto.timingSafeEqual() in Node.js
const crypto = require('crypto'); crypto.timingSafeEqual(Buffer.from(a), Buffer.from(b)) -
88% success Ensure both strings are same length before constant-time comparison
timingSafeEqual requires equal-length buffers. Different lengths immediately reveal inequality. Pad or hash first.
Dead Ends
Common approaches that don't work:
-
Use == to compare API keys or HMAC signatures
85% fail
== returns false at the first differing byte. Comparing 'abc' to 'axc' is faster than 'abc' to 'abd'. Over thousands of requests, attackers can extract the correct value byte by byte.
-
Hash both values and compare hashes with ==
72% fail
Hashing reduces the leak but == comparison of hashes still has timing differences. Use constant-time comparison for the hash comparison too.