密码安全浮动

时间:2016-01-03 10:47:10

标签: javascript random cryptography

如何在Javascript中生成cryptographically secure个浮点数?

这应该是Math.random的插件,范围(0,1),但加密安全。用法示例

cryptoFloat.random();
0.8083966837153522

Secure random numbers in javascript?显示了如何创建加密安全的Uint32Array。也许这可能会以某种方式转换为浮动?

1 个答案:

答案 0 :(得分:4)

由于以下代码非常简单且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)<sup>sign</sup> (1 + Σ<sub>i=1</sub><sup>52</sup> b<sub>52-i</sub> 2<sup>i</sup>) * 2<sup>e-1023</sup>

要将因子设置为1,指数需要为1023.它有11位,因此最高位给出2048.这需要设置为0,其他位设置为1.