Node.js Reference ยท crypto
Node.js crypto.timingSafeEqual() function
Reference for crypto.timingSafeEqual() in Node.js: comparing secrets, MACs and tokens in constant time to prevent timing attacks, with the equal-length rule explained.
crypto.timingSafeEqual(a, b) compares two buffers and returns true if their bytes are identical. Unlike === or Buffer.compare(), it takes the same amount of time whether the first byte differs or only the last one does.
That matters for secrets. A normal comparison stops at the first mismatch, so an attacker who can measure response times might learn a token or signature one byte at a time. Use timingSafeEqual whenever you compare MACs, API tokens, password hashes or any value an attacker could probe.
import { timingSafeEqual } from 'node:crypto'; timingSafeEqual(Buffer.from('abc'), Buffer.from('abc')); // true
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
crypto.timingSafeEqual(a: ArrayBuffer | Buffer | TypedArray | DataView, b: ArrayBuffer | Buffer | TypedArray | DataView): boolean
| Name | Description |
|---|---|
a, b |
The two values to compare. Their byte lengths must be equal. |
Returns: true if every byte matches, otherwise false.
Errors: ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH when the byte lengths differ (the function does not return false here). ERR_INVALID_ARG_TYPE when an argument is not a buffer-like value, such as a string.
Usage notes
- Equal lengths only. The length check itself leaks length, which is usually fine for fixed-size values like HMAC outputs. For variable-length input, hash both sides first, as in the second example.
- Compare bytes, not strings. Convert with
Buffer.from(value)using the same encoding on both sides. Note that typed arrays larger than one byte are compared by their underlying bytes. - Never write your own byte loop. A hand-written comparison in JavaScript can be optimized into an early exit; the built-in is implemented in native code to avoid that.
- It protects only the comparison. If the code that computes or looks up the secret has timing differences, those leak too.
- No need for non-secret data. Comparing public values such as IDs with
===is fine and faster. - Webhook signatures are the classic use: compute the expected HMAC and compare it with the header value using
timingSafeEqual. - Added in Node.js 6.6.0.