javascript - 从数学随机更改为 window.crypto
问题描述
我使用了一个随机词生成器,我想将其更改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了解为什么使用模数%
会降低随机数的熵
推荐阅读
- perl - 如何在 100 个文本文件(每个文件有 50k 行)的 20k 项的“搜索和替换”中进行最少的磁盘 I/O
- python-2.7 - 如何从随机整数创建范围?
- spring-boot - ResourceAssembler 没有在响应_links 中返回正确的路径(创建的资源路径)
- java - Java Apache Beam - 使用 DataflowRunner 保存文件“本地”
- c# - 用于更新从数据库 MVC/Ajax 回调中获取数据的页面部分的回调函数
- c - 什么定义了类型的大小?
- ios - 在 Objective-C 中为 AVAudioEngine 设置录制格式
- xcode - GFortran错误:ld:尝试编译时找不到-lSystem的库
- dialogflow-es - Actions on Google - 无法为 DialogFlow 创建有效版本 - 已知问题?
- linkedin - dnn 在模块中的 linkedin api v2 调用上给出 HttpClient 错误“请求被中止:无法创建 SSL/TLS 安全通道”