Created
December 30, 2021 13:43
-
-
Save urmastalimaa/c0c2d57af63cb12211a4e83e2361e057 to your computer and use it in GitHub Desktop.
v4 UUID generation using crypto.getRandomValues
This file contains hidden or 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
export default function () { | |
// returns an RFC 4122 compliant UUID using the crypto API | |
// Based on https://gist.github.com/bentranter/ed524091170137a72c1d54d641493c1f with | |
// a fix to have padding for numbers < 16 | |
// get sixteen unsigned 8 bit random values | |
let 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 | |
let uid = ''; | |
for (let i = 0; i < u.length; i++) { | |
if (u[i] < 16) { | |
uid += '0'; | |
} | |
uid += u[i].toString(16); | |
if ([3, 5, 7, 9].indexOf(i) > -1) { | |
// includes() is not supported in IE | |
uid += '-'; | |
} | |
} | |
return uid; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment