如何生成cryptographically secure在 Javascript 中 float ?
这应该是 Math.random
的插件,范围为 (0, 1),但加密安全。用法示例
cryptoFloat.random();
0.8083966837153522
Secure random numbers in javascript?展示了如何创建加密安全的 Uint32Array。也许这可以以某种方式转换为 float ?
- The Mozilla Uint32Array documentation不完全清楚如何从 int 转换。
- Google也不是重点。
Float32Array.from(someUintBuf);
总是给出一个整数。
最佳答案
由于以下代码非常简单并且 functionally equivalent to the division method , 这里是 alternate method of altering the bits . (此代码是从@T.J. Crowder 非常有用的回答中复制和修改的)。
// A buffer with just the right size to convert to Float64
let buffer = new ArrayBuffer(8);
// View it as an Int8Array and fill it with 8 random ints
let ints = new Int8Array(buffer);
window.crypto.getRandomValues(ints);
// Set the sign (ints[7][7]) to 0 and the
// exponent (ints[7][6]-[6][5]) to just the right size
// (all ones except for the highest bit)
ints[7] = 63;
ints[6] |= 0xf0;
// Now view it as a Float64Array, and read the one float from it
let float = new DataView(buffer).getFloat64(0, true) - 1;
document.body.innerHTML = "The number is " + float;
解释:
The format of a IEEE754 double是 1 个符号位 (ints[7][7]
),11 个指数位 (ints[7][6]
到 ints[6][5]
),其余为尾数(保存值)。计算公式为
要将因子设置为 1,指数需要为 1023。它有 11 位,因此最高位为 2048。需要将其设置为 0,其他位为 1。
关于javascript - 加密安全 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34575635/