Oliver Jumpertz

Secure Integers In Node

Category: Node.js

Share this snippet to:

const util = require("util");
const { randomInt } = require("crypto");
const randomIntAsync = util.promisify(randomInt);

Usage

You can use both functions as follows:

// sync
const randomInt = randomInt(1, 10);
// async
const asyncRandomInt = await randomIntAsync(1, 10);

Explanation

Good random numbers rely on a lot of entropy (chaos so to say). Math.random does not have much entropy. In fact, there are even good ways to guess which number Math.random probably spills out next when calling it repeatedly. The crypto module in Node doesn’t take any current timestamps or things like that into account and instead relies on more secure entropy.

If you ever need a random number someone should not be able to guess easily, rely on the crypto module instead of Math.random.


Share this snippet to: