Created
September 29, 2016 15:23
-
-
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()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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