What's the right way to base64 encode a binary file on CentOS 7?

$ echo foo |base64 
Zm9vCg==
$ echo foo |base64 |wc -c
9

Note the trailing newline in the output of base64, it's the ninth character here.

For longer input, it'll produce more than one line, as it wraps the output every 76 characters by default. You can disable the wrapping (including the final newline) with base64 -w0, or by piping the output through tr -d '\n'.


base64 writes multiple lines for moderately long strings, so you have to deduct the correct number of newlines from the file size. On some systems, the utility may write a DOS text file (not with base64 from GNU coreutils, but with the implementation from fourmilab common on BSD systems), in which case you will have to deduct 2 bytes per line to get the length of the encoded string.


Responding to question in comments: "How do I get the raw base64 string without any new liens or other garbage? Just the base64 string?"

base64 inserts line breaks after every 76th character since 76 characters is the maximum length of a MIME encoded line of text (and base 64 is most commonly used to create base 64 Content-Transfer-Encoding for emails).

If you want to remove these line breaks:

base64 filename | tr -d '\n\r' >outfilename

With base64 from GNU coreutils, you may use

base64 -w0 filename >outfilename