Skip to content

Instantly share code, notes, and snippets.

@mgd020
Last active June 19, 2020 05:52
Show Gist options
  • Save mgd020/96c646eb4c3b74a1a4adef01877a1b77 to your computer and use it in GitHub Desktop.
Save mgd020/96c646eb4c3b74a1a4adef01877a1b77 to your computer and use it in GitHub Desktop.
Generate a cryptographically random String with a given length
function getRandomBase64String(length) {
var array = new Uint8Array(Math.ceil(length * 3 / 4));
crypto.getRandomValues(array);
return btoa(String.fromCharCode.apply(null, array)).slice(0, length);
}
function getRandomHexString(length) {
var array = new Uint32Array(Math.ceil(length / 8));
crypto.getRandomValues(array);
return Array.prototype.map.call(array, i => i.toString(16).padStart(2, '0')).join('').slice(0, length);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment