代码之家  ›  专栏  ›  技术社区  ›  Arnaud Denoyelle

openssl base64和javascript的btoa之间的差异

  •  0
  • Arnaud Denoyelle  · 技术社区  · 7 年前

    当我尝试使用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 . 算法简单,密码不包含任何特殊字符。那么,什么可以解释这种差异呢?

    2 回复  |  直到 7 年前
        1
  •  4
  •   Jeroen    7 年前

    MAC终端/命令行:

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

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

    但是,当您将命令更改为:

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

    -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.
    
        2
  •  2
  •   oliv    7 年前

    echo 向openssl命令添加新行。

    你应该使用这个选项 -n (无换行符)使用echo命令:

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