Coding Triumph

Helpful code snippets & tutorials

How to generate a cryptographically secure random number in Node.js

Secure random numbers are required for data-sensitive applications, such as generating encryption keys, session ID on a web server, or in password generators that create highly secure passwords. In this tutorial, we’ll see how we can do that using Node.js.

Prerequisite:

Node.js 14.+

1. The wrong way: Math.random()

The Math.random() can be sufficient for some use-cases, but the numbers generated with it can be very predictable. So it’s not cryptographically secure .

/**
 * Returns a random number between min (inclusive) and max (exclusive)
 */
const randomInt = (min, max) => {  
  return Math.floor(
    Math.random() * (max - min) + min
  )
}

// Example:
console.log(  
  between(10, 200)
)

2. The right way: the “crypto” module

const crypto = require("crypto");

const randomInt = (min, max) => {
  const maxBytes = 1;
  // Each byte has a maximum value of 256. so with 4 bytes, the total maximum value is 256^4
  const maxDec = 256 ** maxBytes; //

  // Minimum number should be less than maximum
  if (min >= max) return false;
  // You can not get all possible random numbers if range is greater than "maxDec"
  // "-1" because counting starts from zero.
  if (max - min > maxDec - 1) return false;
  // Maximum number should be under the safe integer limit
  if (max > Number.MAX_SAFE_INTEGER) return false;

  // generate "maxBytes" random bytes
  const buffer = crypto.randomBytes(maxBytes);
  // hexadecimal representation of the buffer
  const hex = buffer.toString('hex');
  // convert to hexadecimal number
  const int = parseInt(hex, 16);
  
  let result = Math.floor((int / maxDec) * (max - min + 1) + min);

  if (result > max) {
    result = max; 
  }
  return result;
};

const random = randomInt(0, 10);

console.log(random);
If you like this post, please share
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments