This content originally appeared on DEV Community and was authored by Kai
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");
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
.
// Synchronous
const n = crypto.randomInt(0, 1000000);
console.log(n);
The third argument is optional. You can provide a callback
function. Then, the random integer is generated asynchronously:
// Asynchronous
crypto.randomInt(0, 1000000, (err, n) => {
if (err) throw err;
console.log(n);
});
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);
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.
This content originally appeared on DEV Community and was authored by Kai
Kai | Sciencx (2021-02-17T14:31:45+00:00) How to Generate a Secure Random Number in Node.js. Retrieved from https://www.scien.cx/2021/02/17/how-to-generate-a-secure-random-number-in-node-js/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.