Last active
May 6, 2019 17:49
-
-
Save adrianorsouza/2b360807064bf9d6ab218b62b076f539 to your computer and use it in GitHub Desktop.
Javascript to generate 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
function createUUID() { | |
// http://www.ietf.org/rfc/rfc4122.txt | |
var s = []; | |
var hexDigits = "0123456789abcdef"; | |
for (var i = 0; i < 36; i++) { | |
s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1); | |
} | |
s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010 | |
s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01 | |
s[8] = s[13] = s[18] = s[23] = "-"; | |
var uuid = s.join(""); | |
return 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
<?php | |
/** | |
* Return a UUID (version 4) using random bytes | |
* Note that version 4 follows the format: | |
* xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx | |
* where y is one of: [8, 9, A, B] | |
* | |
* We use (random_bytes(1) & 0x0F) | 0x40 to force | |
* the first character of hex value to always be 4 | |
* in the appropriate position. | |
* | |
* For 4: http://3v4l.org/q2JN9 | |
* For Y: http://3v4l.org/EsGSU | |
* For the whole shebang: http://3v4l.org/BkjBc | |
* | |
* @link https://paragonie.com/b/JvICXzh_jhLyt4y3 | |
* | |
* @return string | |
*/ | |
function uuidv4() | |
{ | |
return implode('-', [ | |
bin2hex(random_bytes(4)), | |
bin2hex(random_bytes(2)), | |
bin2hex(chr((ord(random_bytes(1)) & 0x0F) | 0x40)) . bin2hex(random_bytes(1)), | |
bin2hex(chr((ord(random_bytes(1)) & 0x3F) | 0x80)) . bin2hex(random_bytes(1)), | |
bin2hex(random_bytes(6)) | |
]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment