Skip to content

Instantly share code, notes, and snippets.

@willwright82
Created October 26, 2017 11:55
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 willwright82/e32395bad60a047fc77dfbce418cb834 to your computer and use it in GitHub Desktop.
Save willwright82/e32395bad60a047fc77dfbce418cb834 to your computer and use it in GitHub Desktop.
Generate a random SHA1 token in browser
// str byteToHex(uint8 byte)
// converts a single byte to a hex string
function byteToHex(byte) {
return ('0' + byte.toString(16)).slice(-2);
}
// str generateId(int len);
// len - must be an even number (default: 40)
function generateId(len) {
var arr = new Uint8Array((len || 40) / 2);
window.crypto.getRandomValues(arr);
return [].map.call(arr, byteToHex).join("");
}
// Ok, let's check it out!
generateId();
// "1e6ef8d5c851a3b5c5ad78f96dd086e4a77da800"
generateId(20);
// "d2180620d8f781178840"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment