I had to convert ttf fonts in Base64 encoding and save them in CSS while doing some more complex stuff. I wrote a python script for it using inbuild base64 library, which worked pretty fine.

I did the same in ruby (with inbuild Base64 library) and my code ran without any error. So far so good! But when I saw the results in browser, I was surprised to see that it replaced the actual glyphs with random glyphs. Since python script output was doing good job, I was surprised, what I did wrong.

When I run the base64 encoding on a shorter string, I noticed the difference in results.

Ruby Run:

irb(main):010:0* require 'base64'
=> false
irb(main):011:0> str="Akash is testing Base64 Encoding between python and ruby"
=> "Akash Agrawal is testing Base64 Encoding between python and ruby"
irb(main):012:0> Base64.encode64(str)
=> "QWthc2ggaXMgdGVzdGluZyBCYXNlNjQgRW5jb2RpbmcgYmV0
d2VlbiBweXRo\nb24gYW5kIHJ1Ynk=\n"

Python Run:

>>> import base64
>>> str="Akash is testing Base64 Encoding between python and ruby"
>>> base64.b64encode(str)
'QWthc2ggaXMgdGVzdGluZyBCYXNlNjQgRW5jb2RpbmcgYmV0
d2VlbiBweXRob24gYW5kIHJ1Ynk='


Please notice that the results in both the languages are same, except ruby appended a line feed ('\n') after every 60 characters.

Surprisingly, on decoding ruby gives same result with both the versions (with and without '\n').

I checked RFC standards and there it was written that
Implementations MUST NOT not add line feeds to base encoded data unless the specification referring to this document explicitly directs base encoders to add line feeds after a specific number of characters.

Though ruby seems to be following some other standards but browsers are complying without '\n' result. TO achieve the same in ruby, one can do the following:

irb(main):018:0> Base64.encode64(str).gsub("\n", '')

PS: In ruby-1.9.2 you have Base64.strict_encode64 which doesn't add that '\n' (newline) at the end.

Subscribe - To get an automatic feed of all future posts subscribe here, or to receive them via email go here and enter your email address in the box. You can also like us on facebook and follow me on Twitter @akashag1001.