javascript / expert
Snippet
Timing-Attack Resistant HMAC Webhook Signature Verification
Standard string comparison operators (===) terminate early upon discovering the first mismatched character. This leaks timing information to malicious actors attempting to forge webhook signatures. In Node.js, crypto.timingSafeEqual evaluates buffer comparison in constant time regardless of where mismatches occur, preventing cryptographic timing attacks.
snippet.js
javascript
1
2
3
4
5
6
7
const crypto = require('node:crypto');function verifySignature(payload, signature, secret) {const hmac = crypto.createHmac('sha256', secret).update(payload).digest();const sigBuffer = Buffer.from(signature, 'hex');if (hmac.length !== sigBuffer.length) return false;return crypto.timingSafeEqual(hmac, sigBuffer);}
nodejs
Breakdown
1
const hmac = crypto.createHmac('sha256', secret).update(payload).digest();
Computes the expected raw SHA256 HMAC digest buffer for the incoming payload.
2
if (hmac.length !== sigBuffer.length) return false;
Validates equal byte lengths before performing constant-time buffer comparisons.
3
return crypto.timingSafeEqual(hmac, sigBuffer);
Executes constant-time comparison to shield against microsecond timing analysis attacks.