javascript / expert
Snippet
Constant-time Comparisons for Cryptographic Integrity
Standard equality operators (==, ===) return as soon as a mismatch is found. This allows attackers to use 'timing attacks' to guess a secret byte-by-byte by measuring response times. timingSafeEqual ensures the comparison always takes the same amount of time regardless of where the mismatch occurs.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
import { timingSafeEqual } from 'node:crypto';function verifyToken(input, actual) {const inputBuf = Buffer.from(input);const actualBuf = Buffer.from(actual);if (inputBuf.length !== actualBuf.length) {return false;}return timingSafeEqual(inputBuf, actualBuf);}
nodejs
Breakdown
1
import { timingSafeEqual } from 'node:crypto';
Imports the specialized comparison function from Node's crypto module.
2
const inputBuf = Buffer.from(input);
Converts strings to Buffers as the function requires Buffer or TypedArray inputs.
3
if (inputBuf.length !== actualBuf.length)
Pre-check length; timingSafeEqual throws an error if buffer lengths differ.
4
return timingSafeEqual(inputBuf, actualBuf);
Executes a constant-time comparison to prevent side-channel leakage.