在 JavaScript 中是否有类似 SecureRandom.hex()
的 (ruby) 函数可以为我生成随机散列?
最佳答案
我被引导到这个问题作为使用以下关键字的顶级搜索引擎结果:
- 安全随机范围 js
- 安全随机 js
因此,我认为最好用今天(2019 年)可用的有效答案更新这篇文章:
下面的代码片段使用了 Crypto.getRandomValues()
用于采购据说是的随机值,
... cryptographically strong ... using a pseudo-random number generator seeded with a value with enough entropy ... suitable for cryptographic usages.
因此,我们有:
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()
以进行直接替换是否适合您的应用程序或目标受众是否纯粹作为学术练习留给实现者。请务必先咨询您的建筑师!当然在这里许可 MIT :)
关于javascript - JavaScript 中的 SecureRandom?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5933282/