在我的node.js服务器端代码中,当尝试创建8位随机数时,结果并不像预期的那样。
我试过下面的代码,
const crypto = require('crypto');
var token = crypto.randomBytes(8);
console.log(token);
它仍然返回bufferred bytearray,它是<Buffer 1d c3 02 b1 d1 0b e9 dc>
。尝试了很多方法来将字节数组转换为8位数字,如98988348(不是十六进制)。
但是仍然不能得到8位随机数。
注意:这里不想使用Math.random()
。
发布于 2021-09-23 09:09:47
crypto.randomInt (Node.js v14.10+/v12.19+)
从Node.js v14.10 (和v12.19)开始,crypto
module导出一个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
https://stackoverflow.com/questions/69296903
复制相似问题