Why ruby Base64 encode 64 add a new line to the end of encoded string

Viewed 29

I am working with 3rd party integrations which require encoding my payload to base64 format. I am using Rails to do this

Base64.encode64("No way") # output: "Tm8gd2F5\n"

Most of the 3rd parties I've worked with do not have any problem with this, however, a few do have problems decoding the encoded value with \n. After facing the issue, I found another version of base64 encoding called strict_encode64

Base64.strict_encode64("No way") # output: "Tm8gd2F5"

which solves the problem.

I am wondering why \n is added to the encoded string.

1 Answers

encode64 uses Array#pack under the hood. It uses the 'm' directive which according to the docs has the rather obscure note "if count is 0, no line feed are added, see RFC 4648". Taking a punt, the reverse might be true - if the count > 0 then add a new line. I've looked through RFC 4648 and can't find any mention of this, but I'm guessing it must in there somewhere.

Sorry if none of that helps. Went down the rabbit hole on this, but maybe there are some crumbs in there that are useful.

Edit: seems that Python also does this and it appears to be deliberate (is specified in their unit tests). So this looks even more like it's related to RFC 4648 (or maybe RFC 2045), but I can't for the life of me find any mention of it in either RFC.

Related