Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's padded Base64 encoded strings and how can i generate them in ruby?

Tags:

json

ruby

base64

Documentation for a Third-Party API that I'm working with states:

"[O]ur API only accepts padded Base64 encoded strings."

What are "padded Base64 encoded strings" and how can I generate them in Ruby. The code below is my first attempt at creating JSON formatted data converted to Base64.

  xa = Base64.encode64(a.to_json)
like image 932
Mohit Jain Avatar asked Aug 04 '11 16:08

Mohit Jain


2 Answers

The padding they are talking about is actually part of Base64 itself. It's the "=" and "==" at the end. Base64 encodes packets of 3 bytes into 4 encoded characters. So if your input data has length n and

  • n % 3 = 1 => "==" at the end for padding
  • n % 3 = 2 => "=" at the end for padding

No need for you to change your code.

like image 72
emboss Avatar answered Oct 25 '22 16:10

emboss


It looks like the base64 library pads by default; padding in Base64 would be the = characters on the end of the data.

You can see this by running the following in the irb console:

irb(main):002:0> require 'base64'
=> true
irb(main):003:0> Base64.encode64('a')
=> "YQ==\n"

Without the padding, you couldn't be sure whether YQ was everything or whether it was missing something.

like image 2
Mark Rushakoff Avatar answered Oct 25 '22 14:10

Mark Rushakoff