How to get a cryptographically strong number in the range [0,1)?
cryptography, javascript, random
Solution
Why not simplify things
function cryptoRandom() {
return window.crypto.getRandomValues(new Uint32Array(1))[0] / 0x100000000;
}
What's going on here?
- Assume `window.crypto.getRandomValues` will giving us truely random bits
- Ask for 32 bits (unsigned integer `i`)
- The `min`ium value of `i` is `0x00000000` (or `0`)
- The `max`imum value of `i` is `0xFFFFFFFF` (or `4294967295`)
- Transform these points onto the range you want; `(i - min) / (max + 1)`
Problem
I've been trying to create a function that will return a random decimal number between 0 (inclusive) and 1 (exclusive) via the `Window.crypto.getRandomValues()` function. Currently, my code is as follows: ``` var rand = function(){ var ra = window.crypto.getRandomValues(new Uint32Array(1))[0]; function dec(n,m){ return (n>=0&&n<=1)?n:dec(n/m,m); } return dec(ra,8); } ``` My problem is that this isn't uniformly distributed; it tends to be between .2 and .7, and rarely falls under .2 and over .7. Is there a better way to use the `.getRandomValues()` method to obtain a number like that of the `Math.random()` function? I am not using the `.random()` method because I wish to have secure numbers for what I am trying to perform.