Timing-safe comparison: why == is wrong for signatures
Ordinary comparison stops at the first mismatch, so the matching prefix length leaks through timing. Compare signatures with a constant-time function.
What leaks
Most string comparisons walk bytes from the start and stop at the first difference. An attacker who varies the signature and measures response time can estimate how many bytes matched. For a 32-byte signature, 256 tries per byte is at most 8,192 attempts in theory.
Network jitter makes the attack hard over the internet, but with a nearby server it is realistic. The defence costs almost nothing, so make it a habit.
Constant-time comparison
A constant-time comparison checks the length, XORs every byte into an accumulator, and returns only the final result. Runtime does not depend on where the values differ.
function timingSafeEqual(a, b) {
if (a.length !== b.length) return false;
let diff = 0;
for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
return diff === 0;
}| Language | Function |
|---|---|
| Node.js | crypto.timingSafeEqual |
| Python | hmac.compare_digest |
| Go | hmac.Equal |
| Java | MessageDigest.isEqual |
| PHP | hash_equals |
Common mistakes
- Comparing hex strings with
==. - Lower-casing a value before comparison instead of normalizing both sides.
- Comparing base64 text without decoding it.
- Assuming an early length check is the main leak; signature lengths are fixed per platform, so the byte loop is what matters.
Standard constant-time helpers often return false immediately when lengths differ. Signature lengths are fixed per platform, so this is not a practical leak, but validating the length first is still good practice.
The timing tab shows exactly how many leading bytes two signatures share.
Open the signature verifierFrequently asked questions
Do timing attacks actually succeed?
There are real cases on local networks and inside data centres where jitter is low. Over the internet it is harder, but the defence is cheap enough to always apply.
Is hashing the signature again before comparison safer?
It fixes the length and blurs timing, but a constant-time comparison is clearer and just as cheap.
Are some default comparisons already safe?
Some runtimes compare short strings in near-constant time, but that is not guaranteed. Use the explicit function.
This guide follows the signing schemes published by GitHub, Stripe, Slack, Shopify and Toss Payments.
← Guides