Last active
January 31, 2022 08:49
-
-
Save lzlrd/c82a8b2397bc6a207531291e52c36fe3 to your computer and use it in GitHub Desktop.
cryptoRandom(), a secure alternative to Math.random() utilising the Web Crypto API.
This file contains hidden or 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
function cryptoRandom() { | |
const cryptoObj = crypto || window.crypto || window.msCrypto; | |
const genArray = cryptoObj.getRandomValues(new Uint8Array(7)); | |
let tmpArray = []; | |
genArray.forEach(function(ele, index) { | |
tmpArray[index] = ele.toString(); | |
if (ele.toString().length < 3) { | |
if (((index === 0) && (Math.random() < 0.1)) || (Math.random() < 0.5)) { | |
tmpArray[index] = ("0" + ele); | |
} | |
} | |
}); | |
return Number("0." + tmpArray.join("")); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment