我使用随机词生成器,我想将其从 math.random
更改为更安全的 window.crypto
。
我试了好几个小时才让它工作,我确信代码中有错误。我必须如何更改我的代码才能使此代码使用 window.crypto
方法?
var wordings = ['X',
'I',
'II'
];
function getRandom(randArray) {
return Math.floor(Math.random() * randArray.length);
}
function showrandom() {
document.getElementById('random').innerHTML = wordings[getRandom(wordings)] + ' ' + wordings[getRandom(wordings)];
}
showrandom();
到目前为止我尝试了什么:
var wordings = ['X',
'I',
'II'
];
function getRandom(randArray) {
var array = new Uint32Array(10);
window.crypto.getRandomValues(array);
}
function showrandom() {
document.getElementById('random').innerHTML = wordings[getRandom(wordings)] + ' ' + wordings[getRandom(wordings)];
}
最佳答案
基本问题是 Math.random
返回从 0(包含)到 1(不包含)的值,而 window.crypto.getRandomValues
返回从 0 到最大 32 位整数的整数(或者您传入的数组类型的最大值)。
因此您需要将 window.crypto
的范围缩小到 Math.random
有点像
function cryptoRandom(){
// return a crypto generated number
// between 0 and 1 (0 inclusive, 1 exclusive);
// Mimics the Math.random function in range of results
var array = new Uint32Array(1),
max = Math.pow(2, 32), // normally the max is 2^32 -1 but we remove the -1
// so that the max is exclusive
randomValue = window.crypto.getRandomValues(array)[0] / max;
return randomValue;
}
function getRandom(randArray) {
return Math.floor(cryptoRandom() * randArray.length);
}
参见 https://news.ycombinator.com/item?id=9976493为什么使用模 %
会降低随机数的熵
关于javascript - 从数学随机更改为 window.crypto,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53257476/