Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
February 17, 2021 02:31 pm GMT

How to Generate a Secure Random Number in Node.js

This post was originally published at kais.blog.

Let's move your learning forward together! Follow me on Twitter for your daily dose of developer tips. Thanks for reading my content!

While you are working on your JavaScript apps, the moment will come when you need a secure random number. Generating it has been quite tricky in the past. Some people use Math.random whenever the need for a random number arises. Please don't do this if there is any chance for an attacker.

If you are generating random numbers for security reasons (e.g. verification codes), you should use a cryptographically secure random number. Fortunately, the crypto module has been extended in recent Node.js versions. So, now there's an easy way to do it in JavaScript.

Prerequisites

  • Node.js (v14.10.0+ / v12.19.0+)

Generate a Secure Random Number Between min and max in JavaScript

Without further ado, let's generate our secure random number. First, import the crypto module:

const crypto = require("crypto");
Enter fullscreen mode Exit fullscreen mode

Now, you have access to the randomInt function. randomInt takes up to three arguments.

Probably, you want to generate a random number in a given range. Therefore, you can specify the minimum (min) and maximum (max). Note that the minimum is inclusive and the maximum is exclusive. So, if you want to generate a number between 0 and 999,999 you'll have to pass 0 and 1000000.

// Synchronousconst n = crypto.randomInt(0, 1000000);console.log(n);
Enter fullscreen mode Exit fullscreen mode

The third argument is optional. You can provide a callback function. Then, the random integer is generated asynchronously:

// Asynchronouscrypto.randomInt(0, 1000000, (err, n) => {  if (err) throw err;  console.log(n);});
Enter fullscreen mode Exit fullscreen mode

Good! Now, n is a secure random integer between 0 and 999999. For example, this could be used as a 6-digit verification code:

const verificationCode = n.toString().padStart("0", 6);
Enter fullscreen mode Exit fullscreen mode

Conclusion

The changes in recent Node.js versions made generating secure random numbers easy. So, if you are generating random numbers to use as verification codes or for a secure random shuffle, you now know how to do it.

Let's move your learning forward together! Follow me on Twitter for your daily dose of developer tips. Thanks for reading my content!

This post was originally published at kais.blog.


Original Link: https://dev.to/kais_blog/how-to-generate-a-secure-random-number-in-node-js-16io

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To