簡體   English   中英

從數學隨機更改為 window.crypto

[英]Change from math random to 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了解為什么使用 modulo %降低隨機數的熵

你錯過了)它應該是document.getElementById('random').innerHTML = wordings[getRandom(wordings)] + ' ' + wordings[getRandom(wordings)]; 這能解決您的問題嗎?

同樣作為文檔顯示 加密,此方法生成隨機整數值。 正如我從您的代碼中了解到的,您正試圖從隨機數中導出wordings數組中單詞的索引。 要從隨機整數中獲取索引,您可以通過wordings.length對每個隨機數使用模運算,但需要根據安全問題對這種方法進行調查。

代碼如下所示:

var wordings = ['X',
    'I',
    'II'
];

function getRandom(randArray){
    var cryptoObj = window.crypto || window.msCrypto; // for IE 11
    var array = new Uint32Array(1);
    cryptoObj.getRandomValues(array);

    return array[0]%randArray.length;
}

function showrandom() {
    document.getElementById('random').innerHTML = wordings[getRandom(wordings)] + ' ' + wordings[getRandom(wordings)];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM