Created
February 20, 2018 19:57
-
-
Save gf3/57c918811375deecc1b33fe88cc1fa28 to your computer and use it in GitHub Desktop.
Generate a secure RFC4122-compliant v4 UUID
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
/** | |
* Convert a number or array of integers to a string of padded hex octets. | |
*/ | |
function asHex(value: number[] | Uint8Array): string { | |
return Array.from(value).map(i => ('00' + i.toString(16)).slice(-2)).join(''); | |
} | |
/** | |
* Attempt to securely generate random bytes/ | |
*/ | |
function getRandomBytes(size: number): number[] | Uint8Array { | |
// SPRNG | |
if ((typeof Uint8Array == 'function') && window.crypto) { | |
let buffer = new Uint8Array(size); | |
return window.crypto.getRandomValues(buffer); | |
} | |
// Insecure random | |
return Array.from(new Array(size), () => Math.random() * 255 | 0); | |
} | |
/** | |
* Generate a RFC4122-compliant v4 UUID. | |
* | |
* @see http://www.ietf.org/rfc/rfc4122.txt | |
*/ | |
export function generateUuid(): string { | |
const version = 0b01000000; | |
const clockSeqHiAndReserved = getRandomBytes(1); | |
const timeHiAndVersion = getRandomBytes(2); | |
clockSeqHiAndReserved[0] &= 0b00111111 | 0b10000000; | |
timeHiAndVersion[0] &= 0b00001111 | version; | |
return [ | |
asHex(getRandomBytes(4)), // time-low | |
'-', | |
asHex(getRandomBytes(2)), // time-mid | |
'-', | |
asHex(timeHiAndVersion), // time-high-and-version | |
'-', | |
asHex(clockSeqHiAndReserved), // clock-seq-and-reserved | |
asHex(getRandomBytes(1)), // clock-seq-loq | |
'-', | |
asHex(getRandomBytes(6)) // node | |
].join(''); | |
} | |
// Default | |
export default generateUuid; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment