openssl base64和javascript的btoa之间的差异

openssl base64和javascript的btoa之间的差异,openssl,base64,Openssl,Base64,当我尝试使用openssl或javascript的btoa函数将字符串编码为base64时,我得到了不同的结果。最后一个字符是不同的 # From a bash terminal on Ubuntu echo 'admin:passw0rd' | openssl base64 # returns YWRtaW46cGFzc3dvcmQK # From Chrome's javascript console btoa('admin:passw0rd') # returns YWRtaW46cGF

当我尝试使用openssl或javascript的btoa函数将字符串编码为base64时,我得到了不同的结果。最后一个字符是不同的

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

# From Chrome's javascript console
btoa('admin:passw0rd')
# returns YWRtaW46cGFzc3cwcmQ=
在线base64编码服务似乎给出了与btoa相同的结果。算法简单,密码不包含任何特殊字符。那么,什么可以解释这种差异呢?

echo在openssl命令中添加了一个换行符

您应该在echo命令中使用选项-n no newline:

echo -n 'admin:passw0rd' | openssl base64
YWRtaW46cGFzc3cwcmQ=
echo向openssl命令添加新行

您应该在echo命令中使用选项-n no newline:

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

刚刚测试过,我确认你的发现:

MAC终端/命令行:

$ echo 'admin:passw0rd' | openssl base64
YWRtaW46cGFzc3cwcmQK
$ echo 'admin:passw0rd' | base64
YWRtaW46cGFzc3cwcmQK
控制台

window.btoa("admin:passw0rd")
"YWRtaW46cGFzc3cwcmQ="
但是,当您将命令更改为:

$ echo -n 'admin:passw0rd' | base64
YWRtaW46cGFzc3cwcmQ=
它给出了相同的结果。默认情况下,echo将向字符串中添加一个换行符,因此您可以将该换行符管道化到base64命令中。通过添加-n,它不会这样做。从手册页:

-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.

刚刚测试过,我确认你的发现:

MAC终端/命令行:

$ echo 'admin:passw0rd' | openssl base64
YWRtaW46cGFzc3cwcmQK
$ echo 'admin:passw0rd' | base64
YWRtaW46cGFzc3cwcmQK
控制台

window.btoa("admin:passw0rd")
"YWRtaW46cGFzc3cwcmQ="
但是,当您将命令更改为:

$ echo -n 'admin:passw0rd' | base64
YWRtaW46cGFzc3cwcmQ=
它给出了相同的结果。默认情况下,echo将向字符串中添加一个换行符,因此您可以将该换行符管道化到base64命令中。通过添加-n,它不会这样做。从手册页:

-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.