Skip to content

Instantly share code, notes, and snippets.

@GitHub30
Forked from alexdiliberto/get_random_bytes.js
Created May 8, 2023 10:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GitHub30/7f678e67da5c64895743db289f5865ae to your computer and use it in GitHub Desktop.
Save GitHub30/7f678e67da5c64895743db289f5865ae 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