javascript / expert
Snippet
Preventing Timing Attacks with crypto.timingSafeEqual in Node.js
Standard string comparisons using '===' terminate early on the first mismatched byte, creating timing side-channels that attackers can exploit to forge signatures byte-by-byte. The crypto.timingSafeEqual function executes comparison operations in constant time regardless of byte alignment, ensuring secret tokens and HMAC digests remain secure.
snippet.js
javascript
1
2
3
4
5
6
7
8
import crypto from 'node:crypto';export function verifySignature(payload, signature, secret) {const hmac = crypto.createHmac('sha256', secret).update(payload).digest();const expectedSig = Buffer.from(signature, 'hex');if (hmac.length !== expectedSig.length) return false;return crypto.timingSafeEqual(hmac, expectedSig);}
nodejs
Breakdown
1
import crypto from 'node:crypto';
Imports the native Node.js cryptography module.
2
const hmac = crypto.createHmac('sha256', secret).update(payload).digest();
Computes a SHA-256 HMAC digest from the input payload.
3
if (hmac.length !== expectedSig.length) return false;
Ensures buffers match in byte length before constant-time comparison.
4
return crypto.timingSafeEqual(hmac, expectedSig);
Compares byte arrays in constant time to prevent side-channel timing attacks.