So I\'ve been doing some digging around and I\'ve been trying to piece together a function that generates a valid v4 UUID in PHP. This is the closest I\'ve been able to come
I'm sure there's a more elegant way to do the conversion from binary to decimal for the 4xxx
and yxxx
portions. But if you want to use openssl_random_pseudo_bytes
as your crytographically secure number generator, this is what I use:
return sprintf('%s-%s-%04x-%04x-%s',
bin2hex(openssl_random_pseudo_bytes(4)),
bin2hex(openssl_random_pseudo_bytes(2)),
hexdec(bin2hex(openssl_random_pseudo_bytes(2))) & 0x0fff | 0x4000,
hexdec(bin2hex(openssl_random_pseudo_bytes(2))) & 0x3fff | 0x8000,
bin2hex(openssl_random_pseudo_bytes(6))
);