我正在尝试在Node.js中准确地生成6随机数字,这需要加密安全。下面是我的代码:
var crypto = require('crypto');
crypto.randomBytes(2, function(err, buffer) {
console.log(parseInt(buffer.toString('hex'), 16));
});问题是,结果可以是4或5数字,因为我们是从十六进制转换为十进制。有没有一种方法可以保持密码安全的函数randomBytes(),同时保证6位数的结果?
发布于 2013-07-08 06:45:32
2个字节的最大值是65535,所以如果你只使用2个字节,你永远不会得到6位数。
改为使用3个字节,然后使用substr将其减少到6位
var crypto = require('crypto');
crypto.randomBytes(3, function(err, buffer) {
console.log(parseInt(buffer.toString('hex'), 16).toString().substr(0,6));
});另一种解决方案是执行randomBytes,直到得到一个6位数的值:
var crypto = require('crypto');
var secureVal = 0;
function generateSecureVal(cb) {
crypto.randomBytes(3, function(err, buffer) {
secureVal = parseInt(buffer.toString('hex'), 16);
if (secureVal > 999999 || secureVal < 100000) {
generateSecureVal(cb);
} else {
cb();
}
});
}
generateSecureVal(function(){
console.log(secureVal);
});上面的问题是,理论上它可能会陷入一个永无止境的循环中,而且它很可能会比第一个例子使用更多的CPU周期。
发布于 2021-12-06 19:53:57
在Node v14.17中添加了一个用于执行此操作的新函数
crypto.randomInt([min, ]max[, callback])得到一个6位数的整数。
const crypto = require('crypto');
crypto.randomInt(100000, 999999, (err, n) => {
if (err) throw err;
console.log(`Random 6 digit integer: ${n}`);
});此外,根据文档https://nodejs.org/api/crypto.html#cryptorandomintmin-max-callback,您还应该通过以下方法检查最小值和最大值是否为安全整数:
Number.isSafeInteger() https://stackoverflow.com/questions/17517038
复制相似问题