Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cryptographically secure float

How do you generate cryptographically secure floats in Javascript?

This should be a plug-in for Math.random, with range (0, 1), but cryptographically secure. Example usage

cryptoFloat.random();
0.8083966837153522

Secure random numbers in javascript? shows how to create a cryptographically secure Uint32Array. Maybe this could be converted to a float somehow?

  • The Mozilla Uint32Array documentation was not totally clear on how to convert from an int.
  • Google was not to the point, either.
  • Float32Array.from(someUintBuf); always gave a whole number.
like image 696
serv-inc Avatar asked Jan 03 '16 10:01

serv-inc


1 Answers

Since the following code is quite simple and functionally equivalent to the division method, here is the alternate method of altering the bits. (This code is copied and modified from @T.J. Crowder's very helpful answer).

// 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;

Explanation:

The format of a IEEE754 double is 1 sign bit (ints[7][7]), 11 exponent bits (ints[7][6] to ints[6][5]), and the rest as mantissa (which holds the values). The formula to compute is

(-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>

To set the factor to 1, the exponent needs to be 1023. It has 11 bits, thus the highest-order bit gives 2048. This needs to be set to 0, the other bits to 1.

like image 106
serv-inc Avatar answered Sep 28 '22 08:09

serv-inc