© 2013 All rights reserved.

Base64.encode64 in Ruby split the resulting string

Be careful when using Base64 library and the encode64 function. Unpleasant feature of this function is that after every 60 characters add to the resulting string “\n”.

This functionality is also described in the documentation:

Returns the Base64-encoded version of bin. This method complies with RFC 2045. Line feeds are added to every 60 encoded characters.

We can look at the function definition:

And try this example:

The result of this example is a string that contains a newlines characters:

Where is the problem

The problem occurs when we decode this string, for example in PHP, which expected to classic base64 string.

The result of this code is as follows:

A string that contains a newline charactes is decoded incorrectly.

The correct solution

The first solution is to do replace these characters with gsub function:

The result is without a newline character:

The correct solution is to use the strict_encode64 function:

The result is the same as that by replacing newlines:

Comments are closed for this page

Hi, i am programmer from the Czech Republic. I love web development (Ruby, Ruby on Rails, PHP, Nette) and iOS development (Objective-C, Cocoa).
To cooperate, here is my phone:
+420 608 836