Skip to content

Instantly share code, notes, and snippets.

@T4cC0re
Created June 19, 2016 14:17
Show Gist options
  • Save T4cC0re/f478b83440de4caf8475060b4da1e286 to your computer and use it in GitHub Desktop.
Save T4cC0re/f478b83440de4caf8475060b4da1e286 to your computer and use it in GitHub Desktop.
Generate a valid UUID v4 using nodejs' CSPRNG
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
.replace(
/[xy]/g,
char => {
const rnd = parseInt(
require('crypto')
.randomBytes(1) // get one byte
.toString('hex')// encode it to hex
.slice(0, 1), // slice to one char
16
); //parse int (ranges from 0-15)
// mask y value and return as hex
return ((char == 'x') ? rnd : (rnd & 0x3 | 0x8)).toString(16);
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment