ser*_*inc 5 javascript random cryptography
如何在Javascript中生成加密安全浮动?
这应该是一个插件Math.random,范围(0,1),但加密安全.用法示例
cryptoFloat.random();
0.8083966837153522
Run Code Online (Sandbox Code Playgroud)
在javascript中保护随机数?展示了如何创建加密安全的Uint32Array.也许这可能会以某种方式转换为浮动?
Float32Array.from(someUintBuf); 总是给出一个整数.由于下面的代码非常简单并且在功能上与除法方法等效,因此这里是更改位的替代方法。(此代码是从@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,指数需要为 1023。它有 11 位,因此最高位给出 2048。这需要设置为 0,其他位为 1。
| 归档时间: |
|
| 查看次数: |
381 次 |
| 最近记录: |