Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between openssl base64 and javascript's btoa

Tags:

openssl

base64

I have different results when I try to encode a string to base64 by using openssl or javascript's btoa function (the last character is different).

# From a bash terminal on Ubuntu
echo 'admin:passw0rd' | openssl base64
# returns YWRtaW46cGFzc3dvcmQK

# From Chrome's javascript console
btoa('admin:passw0rd')
# returns YWRtaW46cGFzc3cwcmQ=

Online base64 encoding services seem to give the same result as btoa. The algorithm is easy and the password does not contain any special character. So what can explain this difference?

like image 888
Arnaud Denoyelle Avatar asked Sep 17 '25 17:09

Arnaud Denoyelle


1 Answers

Just tested, and I confirm your findings:

MAC Terminal / command line:

$ echo 'admin:passw0rd' | openssl base64
YWRtaW46cGFzc3cwcmQK
$ echo 'admin:passw0rd' | base64
YWRtaW46cGFzc3cwcmQK

Console

window.btoa("admin:passw0rd")
"YWRtaW46cGFzc3cwcmQ="

BUT, when you change your command to:

$ echo -n 'admin:passw0rd' | base64
YWRtaW46cGFzc3cwcmQ=

It gives the same result. By default, echo will add a newline character to the string, so you are piping that to the base64 command to. By adding -n it will not do that. From the man pages:

-n    Do not print the trailing newline character.  This may also be achieved by appending `\c' to the end of the string,
       as is done by iBCS2 compatible systems.  Note that this option as well as the effect of `\c' are implementation-
       defined in IEEE Std 1003.1-2001 (``POSIX.1'') as amended by Cor. 1-2002.  Applications aiming for maximum portabil-
       ity are strongly encouraged to use printf(1) to suppress the newline character.
like image 190
Jeroen Avatar answered Sep 19 '25 08:09

Jeroen