Skip to content

Instantly share code, notes, and snippets.

@aeharding
Created September 29, 2016 15:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aeharding/82a7cfc37ca67a4a0f6766105433fe4d to your computer and use it in GitHub Desktop.
Save aeharding/82a7cfc37ca67a4a0f6766105433fe4d to your computer and use it in GitHub Desktop.
Generates a cryptographically secure number [0-1) as an alternative to Math.random()
// Generates a cryptographically secure number [0-1)
// as an alternative to Math.random()
//
// source: http://stackoverflow.com/a/13694869/1319878
function secureRandom() {
var arr = new Uint32Array(2);
crypto.getRandomValues(arr);
// keep all 32 bits of the the first, top 20 of the second for 52 random bits
var mantissa = (arr[0] * Math.pow(2,20)) + (arr[1] >>> 12)
// shift all 52 bits to the right of the decimal point
return mantissa * Math.pow(2,-52);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment