Skip to content

Instantly share code, notes, and snippets.

@alexdiliberto
Created February 25, 2016 16:57
Show Gist options
  • Save alexdiliberto/39a4ad0453310d0a69ce to your computer and use it in GitHub Desktop.
Save alexdiliberto/39a4ad0453310d0a69ce to your computer and use it in GitHub Desktop.
Get random bytes in Javascript (Browser/Node)
let getRandomBytes = (
(typeof self !== 'undefined' && (self.crypto || self.msCrypto))
? function() { // Browsers
var crypto = (self.crypto || self.msCrypto), QUOTA = 65536;
return function(n) {
var a = new Uint8Array(n);
for (var i = 0; i < n; i += QUOTA) {
crypto.getRandomValues(a.subarray(i, i + Math.min(n - i, QUOTA)));
}
return a;
};
}
: function() { // Node
return require("crypto").randomBytes;
}
)();
// Get an array of 18 random bytes where each byte is an integer from range [0,255] inclusive, where [0,255]
// is the range of 8-bit unsigned integers from `new Uint8Array(n)`
let aesKey = getRandomBytes(18)
// Then you can do something like `_.shuffle(aesKey).join('');`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment