SecureRandom in JavaScript?

SecureRandom in JavaScript?

本文关键字:JavaScript in SecureRandom      更新时间:2023-09-26

JavaScript 中是否有一个类似SecureRandom.hex()(ruby)的函数为我生成随机哈希?

使用以下关键字将此问题作为顶级搜索引擎结果引导到:

  • 安全随机范围 JSs
  • 安全随机 js

因此,我认为最好用今天(2019年)可用的工作答案来更新这篇文章:

下面的代码片段使用Crypto.getRandomValues()来获取随机值,据说是,

。加密强度...使用具有足够熵的值播种的伪随机数生成器......适用于加密用途。

因此,我们有:

var N = 32;
var rng = window.crypto || window.msCrypto;
var rawBytes = Array
              .from(rng.getRandomValues(new Uint8Array(N)))
              .map(c => String.fromCharCode(c))
              .join([]);

现在,下面是一个有趣的小十六进制编码器,我使用一些Array函数进行循环,作为单行代码编写:

function hexEncode(s) {
  return s.split('').map(c => (c < String.fromCharCode(16) ? '0' : '') + c.charCodeAt(0).toString(16)).join([]);
}

最后,如果你想结合上述两个来生成随机哈希,你可以直接交换并相应地调整.map()函数,并像这样打包:

function secureRandomHash(N) {
  N = N || 32; // Coalesce if size parameter N is left undefined
  // TODO: Consider refactoring with lazy-loaded function
  // to set preferred RNG provider, else throw an error here
  // to generate noise that no secure RNG is available for
  // this application.
  var rng = window.crypto || window.msCrypto;
  return Array
           .from(rng.getRandomValues(new Uint8Array(N)))
           .map(c => (c < 16 ? '0' : '') + c.toString(16)).join([]);
}

祝您编码愉快!

编辑:事实证明,我最终在我自己的项目中需要它,该项目也实现了上一个示例中建议的 TODO(延迟加载),所以我们来了:

Math.secureRandom = function() {
  var rng = window.crypto || window.msCrypto;
  if (rng === undefined)
    throw 'No suitable RNG found';
  // Lazy-load this if- branch
  Math.secureRandom = function() {
    // More secure implementation of Math.random (https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#Examples)
    return rng.getRandomValues(new Uint32Array(1))[0] / 4294967296;
  };
  return Math.secureRandom();
}

或者,如果您真的很喜欢冒险...

// Auto-upgrade Math.random with a more secure implementation only if crypto is available
(function() {
  var rng = window.crypto || window.msCrypto;
  if (rng === undefined)
    return;
  // Source: https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#Examples
  Math.random = function() {
    return rng.getRandomValues(new Uint32Array(1))[0] / 4294967296;
  };
})();
console.log(Math.random());

扩展Math或覆盖Math.random()以用于直接替换是否适合您的应用程序或目标受众纯粹是作为实施者的学术练习。请务必先咨询您的建筑师!当然,在这里许可麻省理工学院:)

JS中没有这样的帮助程序函数。您可以使用以下方法生成相当随机的哈希:

function hex(n){
 n = n || 16;
 var result = '';
 while (n--){
  result += Math.floor(Math.random()*16).toString(16).toUpperCase();
 }
 return result;
}

您可以修改它以形成一个 GUID:

function generateGuid(){
 var result = '', n=0;
 while (n<32){
  result += (~[8,12,16,20].indexOf(n++) ? '-': '') +    
            Math.floor(Math.random()*16).toString(16).toUpperCase();
 }
 return result;
}