简体   繁体   中英

Convert crypto.randomBytes() to 8 digit random integer

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.

crypto.randomInt (Node.js v14.10+/v12.19+)

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);

crypto.randomBytes

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM