首页 > 解决方案 > 从数学随机更改为 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)];
}

标签: javascripthtmlarrays

解决方案


基本问题是Math.random返回值从 0(包括)到 1(不包括),而window.crypto.getRandomValues返回整数从 0 到最大 32 位整数(或您传入的数组类型的最大值)。

因此,您需要将 的范围缩小window.cryptoMath.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了解为什么使用模数%会降低随机数的熵


推荐阅读