crypto.timingSafeEqual()
Compares two buffers in constant time to prevent timing attacks.
Syntax
crypto.timingSafeEqual(a, b) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
a | Buffer | TypedArray | DataView | Yes | The first value to compare. |
b | Buffer | TypedArray | DataView | Yes | The second value; must be the same byte length as `a`. |
Returns
boolean — true if the buffers are byte-for-byte equal.
Examples
import { timingSafeEqual } from 'node:crypto';
const a = Buffer.from('token-abc');
const b = Buffer.from('token-abc');
console.log(timingSafeEqual(a, b));
Output
true
import { timingSafeEqual } from 'node:crypto';
function safeEqual(x, y) {
const bx = Buffer.from(x);
const by = Buffer.from(y);
return bx.length === by.length && timingSafeEqual(bx, by);
}
console.log(safeEqual('a', 'ab'));
Output
false
Notes
Throws if the two buffers differ in length, which itself leaks
length; guard with a length check that short-circuits before
calling. Use this for comparing API keys, tokens, and HMAC
signatures instead of `===`.