In my node.js server side code, while trying to create 8 digit random number, the result is not as expected.
I tried below code,
const crypto = require('crypto');
var token = crypto.randomBytes(8);
console.log(token);
Still it returns bufferred bytearray which is <Buffer 1d c3 02 b1 d1 0b e9 dc>
.
Tried a lot of methods to convert that byte array to 8 digit number like 98988348(Not a hexadecimal one).
But still not able to get the 8 Digit random number.
Note:Don't want to use Math.random()
here.
As of Node.js v14.10 (and v12.19), the crypto
module exports a randomInt([min], max, [callback])
function which returns a random integer n
such that min <= n < max
. This function inherits all of the security benefits that the crypto
module as a whole provides.
So to get a random 8 digit integer, you'd be looking to invoke the randomInt
function with a min value of 10000000
and a max of 100000000
:
const { randomInt } = require('crypto');
const n = randomInt(10000000, 100000000);
An alternative that doesn't have strict Node.js version requirements would be to convert your buffer to a hex string, and then use the parseInt
function specifying the base
parameter as 16 (for hex).
You can then divide that parsed integer by the largest possible value (0xffffffffffffffff
) to get a cryptographically-secure number between 0 and 1.
Now you just need to multiply this by (max - min)
(90000000 in your case) and then add the min
(10000000).
const { randomBytes } = require('crypto');
const token = crypto.randomBytes(8);
const hex = token.toString('hex');
const min = 10000000;
const max = 100000000;
let n = parseInt(hex, 16); // 0 <= n < 2^64
n /= 0xffffffffffffffff; // 0 <= n < 1
n *= max - min; // 0 <= n < max - min
n += min; // min <= n < max