Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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