security cryptography ai_generated true

Secret comparison vulnerable to timing attack because regular == leaks information via response time

ID: security/timing-attack-string-comparison

Also available as: JSON · Markdown
85%Fix Rate
88%Confidence
3Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
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.

generic

Workarounds

  1. 95% success Use hmac.compare_digest() for constant-time comparison in Python
    import hmac; hmac.compare_digest(received_signature, computed_signature)  # constant time
  2. 95% success Use crypto.timingSafeEqual() in Node.js
    const crypto = require('crypto'); crypto.timingSafeEqual(Buffer.from(a), Buffer.from(b))
  3. 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:

  1. 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.

  2. 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.