Last active
June 19, 2020 05:52
-
-
Save mgd020/96c646eb4c3b74a1a4adef01877a1b77 to your computer and use it in GitHub Desktop.
Generate a cryptographically random String with a given length
This file contains 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
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