Skip to content

Instantly share code, notes, and snippets.

@moritzuehling
Last active November 30, 2015 13:10
Show Gist options
  • Save moritzuehling/f1368dadf57bd12f9d03 to your computer and use it in GitHub Desktop.
Save moritzuehling/f1368dadf57bd12f9d03 to your computer and use it in GitHub Desktop.
(Hopefully) generates a truly random ID-String. It should have an entropy of 6 * length bits. Browser support: IE11+, any other sane browser. ( http://caniuse.com/#search=crypto )
// my usage:
// var userId = generateRandomID(16) // 16 * 6 bits = 96 bits of entropy.
function generateRandomID(length) {
var cryptoObject = (window.crypto || window["msCrypto"]);
if (!cryptoObject || !cryptoObject.getRandomValues) {
throw "No supported cryptography-handler found!";
}
var base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
var array = new Uint8Array(length);
cryptoObject.getRandomValues(array);
var out = "";
for (var i = 0; i < array.length; i++) {
out += base64[array[i] & 63];
}
return out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment