代码之家  ›  专栏  ›  技术社区  ›  serv-inc

加密安全浮点

  •  6
  • serv-inc  · 技术社区  · 10 年前

    您如何生成 cryptographically secure 在Javascript中浮动?

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

    cryptoFloat.random();
    0.8083966837153522
    

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

    1 回复  |  直到 8 年前
        1
  •  7
  •   serv-inc    8 年前

    由于以下代码非常简单,并且 功能等同于除法 ,这里是 更改位的替代方法 。(此代码是从@T.J.Crowder非常有用的答案中复制和修改的)

    //一个大小刚好可以转换为Float64的缓冲区
    let buffer=新的ArrayBuffer(8);
    
    //将其视为Int8Array并用8个随机整数填充
    让ints=新的Int8Array(缓冲区);
    window.crypto.getRandomValues(整数);
    
    //将符号(ints[7][7])设置为0
    //指数(ints[7][6]-[6][5])调整到正确的大小
    //(除最高位外的所有位)
    整数[7]=63;
    整数[6]|=0xf0;
    
    //现在将其视为Float64Array,并从中读取一个浮点
    let float=新数据视图(缓冲区)。getFloat64(0,真)-1;
    document.body。innerHTML=“数字为”+float

    解释:

    IEEE754双精度 的格式为1个符号位( ints[7][7] )、11个指数位( ints[17][6]到 ints[6][5] ),其余为尾数(保留值)。计算公式为

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

    ,这是 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。