密码安全浮动

ser*_*inc 5 javascript random cryptography

如何在Javascript中生成加密安全浮动?

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

cryptoFloat.random();
0.8083966837153522
Run Code Online (Sandbox Code Playgroud)

在javascript中保护随机数?展示了如何创建加密安全的Uint32Array.也许这可能会以某种方式转换为浮动?

  • 关于如何从int转换,Mozilla Uint32Array文档并不完全清楚.
  • 谷歌也没有说到这一点.
  • Float32Array.from(someUintBuf); 总是给出一个整数.

ser*_*inc 6

由于下面的代码非常简单并且在功能上与除法方法等效,因此这里是更改位替代方法。(此代码是从@TJ 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;
Run Code Online (Sandbox Code Playgroud)

解释:

IEEE754 double 的格式是 1 个符号位 ( ints[7][7])、11 个指数位 ( ints[7][6]to 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。