4

I need to convert a username and password combination into base64 before sending to an API.

The javascript BTOA function is working for me, but when I try to use base64 command in bash I get slightly different results.

Javascript:

btoa("hello");                   # aGVsbG8=
btoa("username:password");       # dXNlcm5hbWU6cGFzc3dvcmQ=
btoa("testing");                 # dGVzdGluZw==

Bash:

echo hello | base64              # aGVsbG8K
echo username:password | base64  # dXNlcm5hbWU6cGFzc3dvcmQK
echo testing | base64            # dGVzdGluZwo=

Results are always similar but different.

Server expects the JS style encoding, but I need to use bash.

Why are the results different but similar? How can I produce the results from javascript with bash?

1 Answers1

9

echo "helpfully" adds a newline to the output (based on the specs in the standard), so base64 dutifully encodes that as well.

Tell echo to not add a newline:

$ echo hello | od -c
0000000   h   e   l   l   o  \n
0000006
$ echo -n hello | od -c
0000000   h   e   l   l   o
0000005

Or better, use printf:

$ printf '%s' hello | od -c
0000000   h   e   l   l   o
0000005
$ printf '%s' hello | base64
aGVsbG8=
$ echo -n hello | base64
aGVsbG8=
Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255