Skip to content

Instantly share code, notes, and snippets.

@bentranter
Last active September 1, 2021 11:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bentranter/ed524091170137a72c1d54d641493c1f to your computer and use it in GitHub Desktop.
Save bentranter/ed524091170137a72c1d54d641493c1f 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
@forresto
Copy link

forresto commented Sep 1, 2021

If you're here you might also be interested in this crypto.randomUUID polyfill, but I like how legible the version in this gist is. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment