user3075906
user3075906

Reputation: 745

How to convert a Base64 encoded string to UUID format

How can I convert a Base64 encoded string to a hex encoded string with dashes(basically to uuid format)?

For example if I have

'FWLalpF2T5mmyxS03Q+hNQ0K' 

then how can I convert it to:

1562da96-9176-4f99-a6cb-14b4dd0fa135

Upvotes: 4

Views: 4379

Answers (2)

svoop
svoop

Reputation: 3454

OOPS

The accepted answer has a flaw:

b64 = 'FWLalpF2T5mmyxS03Q+hNQ0K'
b64.unpack("m0").first.unpack("H8H4H4H4H12").join('-')
# => "1562da96-9176-4f99-a6cb-14b4dd0fa135"

Changing the last char in the b64 string results in the same UUID:

b64 = 'FWLalpF2T5mmyxS03Q+hNQ0L'
b64.unpack("m0").first.unpack("H8H4H4H4H12").join('-')
# => "1562da96-9176-4f99-a6cb-14b4dd0fa135"

To prevent this, you might want to hash your input (base64 or anything else) to the correct length e.g. with MD5:

require "digest"
b64 = 'FWLalpF2T5mmyxS03Q+hNQ0K'
Digest::MD5.hexdigest(b64).unpack("a8a4a4a4a12").join('-')
# => "df71c785-6552-a977-e0ac-8edb8fd63f6f"

Now the full input is relevant, altering the last char results in a different UUID:

require "digest"
b64 = 'FWLalpF2T5mmyxS03Q+hNQ0L'
Digest::MD5.hexdigest(s).unpack("a8a4a4a4a12").join('-')
# => "2625f170-d05a-f65d-38ff-5d9a7a972382"

Upvotes: 3

Beartech
Beartech

Reputation: 6411

I was familiar with unpack but this prompted me to learn the directive as pointed out by cremno.

simplest form:

b64 = 'FWLalpF2T5mmyxS03Q+hNQ0K'
b64.unpack("m0").first.unpack("H8H4H4H4H12").join('-')

#=> "1562da96-9176-4f99-a6cb-14b4dd0fa135"

b64.unpack("m0") 

give us:

#=> ["\x15b\xDA\x96\x91vO\x99\xA6\xCB\x14\xB4\xDD\x0F\xA15\r\n"]

which is an array so we use .first to grab the string and unpack again using the directive to format it in the 8-4-4-4-12 format:

b64.unpack("m0").first.unpack("H8H4H4H4H12")

gives us:

#=> ["1562da96", "9176", "4f99", "a6cb", "14b4dd0fa135"]

an array of strings, so now we just join it with the -:

b64.unpack("m0").first.unpack("H8H4H4H4H12").join('-')

#=> "1562da96-9176-4f99-a6cb-14b4dd0fa135"

Upvotes: 8

Related Questions