-
-
Save GitHub30/7f678e67da5c64895743db289f5865ae to your computer and use it in GitHub Desktop.
Get random bytes in Javascript (Browser/Node)
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
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