1

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.

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

1

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
  • How do I get the raw base64 string without any new liens or other garbage? Just the base64 string? – Dave May 31 '18 at 20:45
  • @Dave See updated answer. – Kusalananda May 31 '18 at 20:51
0

Per the manual:

SYNOPSIS
       base64 [OPTION]... [FILE]

DESCRIPTION
       Base64 encode or decode FILE, or standard input, to standard output.

       With no FILE, or when FILE is -, read standard input.

It sounds like what you're doing is right, but I would instead rather than invoking a useless use of cat, suggest something like base64 file > file.b64.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.