Created
October 26, 2017 11:55
-
-
Save willwright82/e32395bad60a047fc77dfbce418cb834 to your computer and use it in GitHub Desktop.
Generate a random SHA1 token in browser
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
// 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
Original from: https://stackoverflow.com/questions/9407892/how-to-generate-random-sha1-hash-to-use-as-id-in-node-js