Skip to content

Instantly share code, notes, and snippets.

@mohan-mu
Forked from bentranter/uuid_v4.js
Created July 17, 2020 11:10
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 mohan-mu/3ac59ddf9d55583416e0d1acaf2b345f to your computer and use it in GitHub Desktop.
Save mohan-mu/3ac59ddf9d55583416e0d1acaf2b345f to your computer and use it in GitHub Desktop.
Spec Compliant UUIDv4 Generator using the Web Crypto API
// uuid returns an RFC 4122 compliant universally unique
// identifier using the crypto API
function uuid() {
// get sixteen unsigned 8 bit random values
var u = window
.crypto
.getRandomValues(new Uint8Array(16));
// set the version bit to v4
u[6] = (u[6] & 0x0f) | 0x40
// set the variant bit to "don't care" (yes, the RFC
// calls it that)
u[8] = (u[8] & 0xbf) | 0x80
// hex encode them and add the dashes
var uid = "";
uid += u[0].toString(16);
uid += u[1].toString(16);
uid += u[2].toString(16);
uid += u[3].toString(16);
uid += "-";
uid += u[4].toString(16);
uid += u[5].toString(16);
uid += "-";
uid += u[6].toString(16);
uid += u[7].toString(16);
uid += "-";
uid += u[8].toString(16);
uid += u[9].toString(16);
uid += "-";
uid += u[10].toString(16);
uid += u[11].toString(16);
uid += u[12].toString(16);
uid += u[13].toString(16);
uid += u[14].toString(16);
uid += u[15].toString(16);
return uid;
}
// outputs something like:
// 6fc4b899-44af-4092-a0ee-b391e90eef12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment