Centos – What’s the right way to base64 encode a binary file on CentOS 7

base64binarycentoscharacter encoding

I'm using CentOS 7 with bash shell. I thought base64-encoding a binary file would be as simple as

[rails@server lib]$ cat mybinary.file | base64 > /tmp/output.base64

However, I notice when I look at the file length, it's not a multiple of four

[rails@server lib]$ ls -al /tmp/output.base64 
-rw-rw-r-- 1 rails rails 92935 May 31 15:50 /tmp/output.base64

I don't know if what I have done is valid or not, but when I try and decode the file with a JS library I get an error complaining about the fact that the string length is not a multiple of four, so I'm wondering if what I did above is correct or if there's some other way to do it.

Best Answer

$ 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'.

Related Question