在我的node.js服务器端代码中,当尝试创建8位随机数时,结果不像预期的那样。
我试过下面的代码,
const crypto = require('crypto');
var token = crypto.randomBytes(8);
console.log(token);
它仍然返回缓冲的字节数组,即<Buffer 1d c3 02 b1 d1 0b e9 dc>
。尝试了很多方法将字节数组转换为8位数字,如98988348(不是十六进制)。
但仍无法获得8位随机数
注意:此处不要使用Math.random()
crypto。randomInt (Node.js v14.10+/v12.19+)
在Node.js v14.10(和v12.19)中,crypto
模块导出一个randomInt([min], max, [callback])
函数,该函数返回一个随机整数n
,以便min <= n < max
。这个函数继承了crypto
模块作为一个整体提供的所有安全优势。
因此,为了获得一个随机的8位整数,您需要调用randomInt
函数,其最小值为10000000
,最大值为100000000
:
const { randomInt } = require('crypto');
const n = randomInt(10000000, 100000000);
crypto.randomBytes
一个没有严格Node.js版本要求的替代方法是将缓冲区转换为十六进制字符串,然后使用parseInt
函数指定base
参数为16(十六进制)。
然后,您可以将解析后的整数除以可能的最大值(0xffffffffffffffff
),以获得0到1之间的加密安全数字。
现在你只需要乘以(max - min)
(90000000),然后加上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