A Reminder about Base64#encode64 in Ruby

Some days ago I was in a integration with a third-party service, so I ended up making use of an HTTP authorization header.

As normal, I needed to pass username and password base64-encoded in the format "username:password".

The first thing on my mind was to use Base64#encode64 from Ruby's standard library as usual (see the snippet below).

require 'base64'

Base64.encode64('myusername:mysuperpassword')

However, I could not authenticate, I just received the following error message "':' is missing".

Not for the first time, after a while dealing with this particular issue, I found out the reason. As very well documented, encode64 adds a \n to every 60 encoded chars in the output string.

require 'base64'

Base64.encode64('a') # => "YQ==\n"
Base64.encode64('a') == "YQ==" # => false

As solution, we could use Base64#strict_encode64 or keep Base64#encode64 and then replace \n occurrences. See below:

require 'base64'

Base64.strict_encode64('a') # => "YQ=="
Base64.strict_encode64('a') == "YQ==" # => true
require 'base64'

Base64.encode64('a') # => "YQ==\n"
Base64.encode64('a').gsub("\n", '') == "YQ==" # => true

But the first approach is faster (2x at least on avg):

puts Benchmark.measure { 5000.times{ Base64.strict_encode64('a')  } }

0.010000 0.000000 0.010000 ( 0.009167)
puts Benchmark.measure { 5000.times{ Base64.encode64('a').gsub("\n", '')  } }

0.020000 0.000000 0.020000 ( 0.024225)

I hope don't forget it anymore.

See you.

Written on September 27, 2014

Share: