228
$ echo -n "apfjxkic-omyuobwd339805ak:60a06cd2ddfad610b9490d359d605407" | base64
YXBmanhraWMtb215dW9id2QzMzk4MDVhazo2MGEwNmNkMmRkZmFkNjEwYjk0OTBkMzU5ZDYwNTQw
Nw==

The output has a return before Nw==. What is the correct way to generate base64 in Linux?

terminal screenshot

psmears
  • 549
Tiina
  • 3,297

4 Answers4

373

Try:

echo -n "apfjxkic-omyuobwd339805ak:60a06cd2ddfad610b9490d359d605407" | base64 -w 0

From man base64:

-w, --wrap=COLS
Wrap encoded lines after COLS character (default 76). Use 0 to disable line wrapping.

A likely reason for 76 being the default is that Base64 encoding was to provide a way to include binary files in e-mails and Usenet postings which was intended for humans using monitors with 80 characters width. Having a 76-character width as default made that usecase easier.

87

On systems where the -w option to base64 is not available (e.g. Alpine Linux, an Arch Linux initramfs hook, etc.), you can manually process the output of base64:

base64 some_file.txt | tr -d \\n

This is the brute-force approach; instead of getting the program to co-operate, I am using tr to indiscriminately strip every newline on stdout.

7

So please use echo -n to remove the line break before redirecting to base64; and use base64 -w 0 to prevent base64 itself to add line break into the output.

me@host:~ 
$ echo -n mypassword | base64 -w 0
bXlwYXNzd29yZA==me@host:~ # <<<<<<<<<<<<<<< notice that no line break added after "==" due to '-w 0'; so me@host is on the same line
$ echo -n 'mypassword' | base64 -w 0
bXlwYXNzd29yZA==me@host:~ # <<<<<<<<<<<<<<<<<< notice adding single quotes does not affect output, so you can use values containing spaces freely

A good way to verify is using od -c to show the actual chars.

me@host:~ 
$ echo -n bXlwYXNzd29yZA== | base64 -d | od -c
0000000   m   y   p   a   s   s   w   o   r   d
0000012

You see no "\n" is added. But if you use "echo" without "-n", od will show "\n":

me@host:~ 
$ echo mypassword | base64 -w 0
bXlwYXNzd29yZAo=me@host:~ 
$ echo bXlwYXNzd29yZAo= | base64 -d | od -c
0000000   m   y   p   a   s   s   w   o   r   d  \n
0000013

At last, create a function will help you in the future:

base64-encode() {
    if [ -z "$@" ]; then
        echo "Encode string with base64; echoing without line break, and base64 does not print line break neither, to not introducing extra chars while redirecting. Provide the string to encode. "
        return 1
    fi
    echo -n "$@" | base64 -w 0  # here I suppose string if containing space is already quoted
}
5

For anyone using openssl base64, you can use the -A flag:

 -A                 Process base64 data on one line (requires -a)
 -a                 Perform base64 encoding/decoding (alias -base64)

The following worked for me:

echo -n '{string}' | openssl base64 -A
Redtama
  • 151