How to Protect Against Timing Attacks
Compare secrets in constant time, equalise visible work, and close the timing side channels that leak values byte by byte.
On this page
Introduction
A timing attack recovers a secret by measuring how long a comparison takes rather than by breaking the cryptography. A naive string comparison returns as soon as it finds a difference, so matching one more leading character takes a little longer, and an attacker who repeats the request millions of times can read the secret out one byte at a time. The same class of leak appears in password checks, token validation, MAC verification, and even in how long a lookup for a missing user takes versus an existing one. This article explains where timing leaks live and how to close them.
What a Timing Attack Is
A timing attack exploits the fact that different inputs cause different amounts of work. If comparing a guess to the real secret takes longer the more characters match, the duration is a signal about the secret. An attacker who can measure durations with enough precision and repetition averages away the noise and recovers the value. The attack does not need to see the secret; it only needs to observe a duration that depends on it.
The threat is most acute over the network for short secrets and for high-value comparisons, but it is not limited to them. Even with network jitter an attacker can take many samples; and an attacker with local access, a shared cache, or a co-located process has far finer timing. Assume your comparison leaks unless you have made it constant-time.
Where Timing Leaks
The obvious case is comparing a supplied token to a stored one with a normal string equality, which short-circuits on the first mismatch. Password verification that checks a plaintext password is the same failure. MAC and HMAC verification with a naive byte-by-byte compare is another, and it is especially dangerous because the MAC protects integrity.
Less obvious are the branches around the comparison. A login that returns quickly when the username does not exist and more slowly when it does leaks which usernames are valid. A password check that skips the hash computation for an unknown user is fast for unknown users and slow for known ones. An authorization check that queries the database only when a token is well-formed leaks whether the format was right.
Constant-Time Comparison
A constant-time comparison examines every byte regardless of where the first difference is, so the running time depends only on the length, not the content. Compare lengths first (length is usually not secret), then accumulate the difference of every pair and check whether the total is zero. Use a library primitive where one exists, because getting this right by hand is easy to get subtly wrong.
const { timingSafeEqual } = require('node:crypto');
// Correct: timingSafeEqual from the standard library.
function safeCompare(a, b) {
const ba = Buffer.from(a);
const bb = Buffer.from(b);
if (ba.length !== bb.length) return false; // length is not secret
return timingSafeEqual(ba, bb);
}
// Illustrative constant-time integer comparison (for learning only;
// prefer the library primitive above).
function constantTimeEqual(a, b) {
if (a.length !== b.length) return false;
let diff = 0;
for (let i = 0; i < a.length; i++) {
diff |= a.charCodeAt(i) ^ b.charCodeAt(i); // no early exit
}
return diff === 0;
}
Mitigating Enumeration
Even with a constant-time comparison, the surrounding flow can leak. If an unknown user short-circuits before the expensive hash, the response is measurably faster. The fix is to perform the same work in both cases: hash the supplied password against a dummy hash when the user does not exist, so the unknown-user path costs the same as the known-user path. Then the response time does not reveal existence.
// Always run the hash verification, even for an unknown user.
const DUMMY_HASH = '$2b$12$............................'; // precomputed
async function verifyLogin(username, password) {
const user = await findUser(username);
const hash = user ? user.passwordHash : DUMMY_HASH;
const ok = await bcrypt.compare(password, hash); // same cost either way
return user && ok; // do not branch earlier
}
// Response must not differ by existence: return the same status and body.
function loginResponse(exists) {
return exists
? { message: 'invalid credentials' }
: { message: 'invalid credentials' }; // identical
}
Broader Timing Channels
Timing leaks also appear outside direct comparisons. Cache behaviour differs for hits and misses, and an attacker sharing the cache can measure it. Compression ratio reveals repetition in data, which is the basis of the BREACH and CRIME attacks against compressed responses containing both a secret and attacker-controlled input. Errors that take different amounts of work, such as a parse that fails early versus late, leak the shape of the input.
Mitigations include disabling compression on responses that mix secrets with user input, ensuring error paths take comparable time, and avoiding data-dependent table lookups in cryptographic code (where a real risk of cache-timing exists). At the application layer, the practical rules are: use constant-time comparison for secrets, keep the work before the comparison independent of the secret, and do not let error paths reveal the input’s structure.
Testing for Timing
You can check that a comparison is constant-time by measuring many iterations with differing inputs and asserting the durations do not separate by input. This is noisy in a unit test but useful when run with enough samples and a generous threshold; a clear difference is worth investigating. Static review is often more effective: grep for equality operators used on secrets and tokens and confirm each is replaced by a constant-time primitive.
Write the rule into code review: any comparison involving a secret, token, MAC or password must use the constant-time function, and any flow that branches on whether a user or token exists must have identical timing on both paths. Tests can assert that a login with an unknown user and a wrong password return the same response and take comparable time, which catches the most common regression.
Conclusion
Timing attacks turn the duration of a comparison into information about the secret. Close the direct leak with a constant-time comparison for every check involving a secret, MAC or password, and close the indirect leak by making the work before the comparison independent of whether the target exists: hash against a dummy value for unknown users and return identical responses. Beware cache, compression and error-path channels, and enforce constant-time comparison in review so it cannot regress. Then the server’s response time says nothing an attacker can use.
Sources: Node.js crypto.timingSafeEqual, OWASP: Timing attacks, Bcrypt and timing.
FAQ
- Is network jitter enough to hide timing differences?
- No. An attacker can take many samples and average out the noise, especially for a deliberate, patient attack. Assume the difference is measurable and make the comparison constant-time rather than relying on jitter to blur it.
- Why hash a dummy value for an unknown user?
- So the unknown-user path costs the same as the known-user path. If the code skips the hash when the user does not exist, the response is measurably faster, which tells an attacker the username is invalid and enables account enumeration.
Report a problem with this articleOpens a pre-filled issue on GitHub.