当我尝试使用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
相同的结果。该算法很简单,密码不包含任何特殊字符。那么,什么可以解释这种差异呢?
答案 0 :(得分:1)
echo
向openssl命令添加换行符。
您应该在echo命令中使用选项-n
(无换行符):
echo -n 'admin:passw0rd' | openssl base64
YWRtaW46cGFzc3cwcmQ=
答案 1 :(得分:1)
刚刚测试,我确认您的发现:
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.