Why does the base64 of a string contain "\n"?
Andrew Mclaughlin
$ 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?
2 Answers
Try:
echo -n "apfjxkic-omyuobwd339805ak:60a06cd2ddfad610b9490d359d605407" | base64 -w 0From man base64:
-w,--wrap=COLS
Wrap encoded lines afterCOLScharacter (default76). Use0to 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.
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 \\nThis is the brute-force approach; instead of getting the program to co-operate, I am using tr to indiscriminately strip every newline on stdout.