Difficulty: Advanced
What is a timing attack, how does it fit into the broader family of side-channel attacks, and how do you defend against it?
A timing attack is a side-channel attack where the attacker learns secret information by measuring how long an operation takes. The computation itself is correct and the output reveals nothing directly, but the time it takes leaks information about the secret. A side channel is any observable physical or timing property of a system, as opposed to a flaw in the algorithm on paper.
Many naive comparisons return as soon as they find a mismatch. If a password, API token or HMAC is compared byte by byte and the function exits on the first wrong byte, then a guess with a correct first byte takes slightly longer than one that is wrong immediately. By sending many guesses and measuring tiny timing differences, an attacker can recover a secret one byte at a time. The same idea applies to cryptographic code whose running time depends on secret key bits, such as a modular exponentiation that branches on key values.
| Channel | What leaks | Example |
|---|---|---|
| Timing | Execution duration | Non-constant-time string compare |
| Cache | Memory access patterns | Spectre and Meltdown reading across boundaries |
| Power analysis | Power draw during crypto | Extracting keys from a smart card |
| Electromagnetic | EM emissions | Reading a device's operations from nearby |
| Acoustic | Sound of components | Inferring keystrokes or CPU activity |
| Error/oracle | Differing error responses | Padding oracle attacks on CBC |
Side channels are powerful because they bypass the mathematics. An algorithm can be provably secure yet still leak its key through how it runs on real hardware.
crypto.timingSafeEqual in Node, hmac.compare_digest in Python, or subtle.ConstantTimeCompare in Go.You rarely implement ciphers, but you do compare secrets: verifying an HMAC signature on a webhook, checking an API token, or comparing a password reset token. Using == there is a real, exploitable timing leak. Always use a constant-time comparison for anything secret.
== or ===, which short-circuits on the first mismatch.import { timingSafeEqual } from 'node:crypto';
// LEAKY: === short-circuits on the first differing character
function unsafeCheck(a, b) {
return a === b;
}
// SAFE: constant-time, independent of where bytes differ
function safeCheck(a, b) {
const bufA = Buffer.from(a);
const bufB = Buffer.from(b);
// lengths must match; compare a fixed-length digest if they vary
if (bufA.length !== bufB.length) return false;
return timingSafeEqual(bufA, bufB);
}
timingSafeEqual always scans the whole buffer, so the runtime does not reveal how many leading bytes matched. For variable-length secrets, compare fixed-length HMACs of both values instead.
Side-Channel, Timing Attack, Constant-Time Comparison, Cryptography