Open In App

Node.js crypto.timingSafeEqual() Function

Node.js is a cross-platform, open-source back-end JavaScript runtime environment that uses the V8 engine to execute JavaScript code outside of a web browser. Node.js allows developers to utilize JavaScript to create command-line tools and server-side scripting, which involves running scripts on the server before sending the page to the user’s browser. Cryptographic functionality is provided via the crypto module, which includes wrappers for OpenSSL’s hash, HMAC, cypher, decode, sign, and verify methods.

The crypto.timingSafeEqual() function is used to determine whether two variables are equal without exposing timing information that may allow an attacker to guess one of the values. A constant-time algorithm underpins it.



Syntax:

crypto.timingSafeEqual(a, b)

Parameters:



Return Value: true if a is equal to b, else false.

Example 1:




import crypto from 'crypto';
  
const a = Buffer.alloc(5, 'b');
const b = Buffer.alloc(5, 'b');
  
let res = crypto.timingSafeEqual(a, b);
console.log(res);

Output:

true

Example 2:




import crypto from 'crypto';
  
const a = new Int8Array(8);
const b = new Int8Array(a);
a[0] = 2;
b[1] = 5;
  
let res = crypto.timingSafeEqual(a, b);
console.log(res);

Output:

false

Reference: https://nodejs.org/dist/latest-v12.x/docs/api/crypto.html#crypto_crypto_timingsafeequal_a_b

Article Tags :