javascript - 加密安全 float

标签 javascript random cryptography

如何生成cryptographically secure在 Javascript 中 float ?

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

cryptoFloat.random();
0.8083966837153522

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

最佳答案

由于以下代码非常简单并且 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。

关于javascript - 加密安全 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34575635/

相关文章:

Java:如何为文件创建 SHA-1?

binary - 如何解码这个二进制消息?

javascript - 绘制从 View PHP 发送到 Javascript 函数的数组

javascript - 如何在asp.net中从c#设置<h4>的文本

python - 将数分成随机数的随机元素?

algorithm - 修改均匀随机数生成器的范围

javascript - 我们可以使用给定的字符串模式创建 XRP 帐户地址并使用校验和完成其余部分吗?

javascript - 按键值过滤json对象

javascript - 按下按钮加载更多名称时从网站收集名称