Why does the base64 of a string contain "\n"?
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Horror Game Menu Looping
--
Chapters
00:00 Question
00:31 Accepted answer (Score 331)
01:24 Answer 2 (Score 81)
01:55 Answer 3 (Score 3)
02:16 Thank you
--
Full question
https://superuser.com/questions/1225134/...
Question links:
[image]: https://i.stack.imgur.com/io3Cd.png
Accepted answer links:
[man base64]: https://linux.die.net/man/1/base64
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#base64
#avk47
ACCEPTED ANSWER
Score 367
Try:
echo -n "apfjxkic-omyuobwd339805ak:60a06cd2ddfad610b9490d359d605407" | base64 -w 0
From man base64
:
-w
,--wrap=COLS
Wrap encoded lines afterCOLS
character (default76
). Use0
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.
ANSWER 2
Score 85
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.
ANSWER 3
Score 6
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
}
ANSWER 4
Score 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