Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

base 64 URL decode with Ruby/Rails?

I am working with the Facebook API and Ruby on Rails and I'm trying to parse the JSON that comes back. The problem I'm running into is that Facebook base64URL encodes their data. There is no built-in base64URL decode for Ruby.

For the difference between a base64 encoded and base64URL encoded, see wikipedia.

How do I decode this using Ruby/Rails?

Edit:

Because some people have difficulty reading - base64 URL is DIFFERENT than base64

like image 451
sethvargo Avatar asked Jan 17 '11 00:01

sethvargo


3 Answers

Dmitry's answer is correct. It accounts for the '=' sign padding that must occur before string decode. I kept getting malformed JSON and finally discovered that it was due to the padding. Read more about base64_url_decode for Facebook signed_request.

Here's the simplified method I used:

 def base64_url_decode(str)
   str += '=' * (4 - str.length.modulo(4))
   Base64.decode64(str.tr('-_','+/'))
 end
like image 141
awaage Avatar answered Nov 06 '22 20:11

awaage


Googling for "base64 for URL ruby" and choosing the first result lead me to the answer

 cipher_token = encoded_token.tr('-_','+/').unpack('m')[0]

The details of the cipher_token aren't important save that it can contain any byte values.

You could then, of course, make a helper to base64UrlDecode( data ).

What's happening is that it takes the encoded_token and replaces all the - and _ characters with + and /, respectively. Then, it decodes the base64-encoded data with unpack('m') and returns the first element in the returned array: Your decoded data.

like image 5
davemyron Avatar answered Nov 06 '22 21:11

davemyron


For base64URL-encoded string s...

s.tr('+/', '-_').unpack('m')[0]
like image 5
DigitalRoss Avatar answered Nov 06 '22 22:11

DigitalRoss