Last active
November 30, 2015 13:10
-
-
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 )
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
// 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