Last active
March 30, 2018 00:28
-
-
Save spangenberg/ddf53f4b06d48f7d70aa4d7b543895a2 to your computer and use it in GitHub Desktop.
SecureRandom#base64_urlsafe_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
module Random::Formatter | |
# SecureRandom.base64_urlsafe_uuid generates a random v4 UUID (Universally Unique IDentifier) base64 string. | |
# | |
# p SecureRandom.base64_urlsafe_uuid #=> "bg4vleJWQvuhyikuUJy3MA" | |
# p SecureRandom.base64_urlsafe_uuid #=> "KQn-06XIT3ShqWaZz4kXuA" | |
# p SecureRandom.base64_urlsafe_uuid #=> "jlu3dBFcQb-8MTAfoOZXRg" | |
# | |
# The version 4 UUID is purely random (except the version). | |
# It doesn't contain meaningful information such as MAC addresses, timestamps, etc. | |
# | |
# The result contains 122 random bits (15.25 random bytes). | |
# | |
# See RFC 4122 for details of UUID. | |
# | |
# The uuid format produces 36 bytes and the base64 encoded format produces 22 bytes. | |
# This format has the advantage of saving 14 bytes per uuid. | |
def base64_urlsafe_uuid | |
ary = random_bytes(16).unpack("NnnnnN") | |
ary[2] = (ary[2] & 0x0fff) | 0x4000 | |
ary[3] = (ary[3] & 0x3fff) | 0x8000 | |
bin = ["%08x%04x%04x%04x%04x%08x" % ary].pack('H*') | |
[bin].pack("m0").tr("+/", "-_").delete("=") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment