Skip to content

Instantly share code, notes, and snippets.

@lzlrd
Last active January 31, 2022 08:49
Show Gist options
  • Save lzlrd/c82a8b2397bc6a207531291e52c36fe3 to your computer and use it in GitHub Desktop.
Save lzlrd/c82a8b2397bc6a207531291e52c36fe3 to your computer and use it in GitHub Desktop.
cryptoRandom(), a secure alternative to Math.random() utilising the Web Crypto API.
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