base 64 URL decode with Ruby/Rails? base 64 URL decode with Ruby/Rails? json json

base 64 URL decode with Ruby/Rails?


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


For base64URL-encoded string s...

s.tr('+/', '-_').unpack('m')[0]


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.