Skip to content

Instantly share code, notes, and snippets.

@adrianorsouza
Last active May 6, 2019 17:49
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save adrianorsouza/2b360807064bf9d6ab218b62b076f539 to your computer and use it in GitHub Desktop.
Save adrianorsouza/2b360807064bf9d6ab218b62b076f539 to your computer and use it in GitHub Desktop.
Javascript to generate UUID
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;
}
<?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