Skip to content

Instantly share code, notes, and snippets.

@AlastairTaft
Last active September 23, 2020 23:45
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 AlastairTaft/294e88c5105a79d40fd57707856627d4 to your computer and use it in GitHub Desktop.
Save AlastairTaft/294e88c5105a79d40fd57707856627d4 to your computer and use it in GitHub Desktop.
Generates a URL safe key with sufficient bit complexity
/**
* Generate a URL safe key with sufficient bits of complexity.
*/
const generateKey = function(bits){
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "abcdefghijklmnopqrstuvwxyz"
+ "012345678910"
+ "-_"
var expectedEntroy = Math.pow(2, bits)
var key = ''
while(Math.pow(alphabet.length, key.length) < expectedEntroy){
key += alphabet[Math.floor(Math.random() * alphabet.length)]
}
return key
}
// Will result in at least 256 bits of entropy
console.log(generateKey(256))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment