php base64_encode结果与javascript编码结果不相似

时间:2017-06-15 17:46:30

标签: javascript php node.js

代码段:

PHP:

$shaVal = '59bc125840733ea828f42e276661b01e177f1414';

$enc = base64_encode(pack('H*', $shaVal));

echo $enc;

//prints => WbwSWEBzPqgo9C4nZmGwHhd/FBQ=

在Javascipt中我使用了buffer npm模块

let Buffer = require('buffer').Buffer;

let shaVal = '59bc125840733ea828f42e276661b01e177f1414';

//function similar to php's pack() and returns binary data 
let bData = Buffer.from(shaVal, 'hex').toString();
console.log('bData ', bData)

//encode with base64
let val64 = Buffer.from(bData, 'binary').toString('base64');
console.log('base 64 encode ', val64)

//prints => Wf0SWEBzPv0o/S4nZmH9Hhd/FBQ=

如何获得由php打印的完全相同的输出?

注意:两个选项都显示二进制数据为Y�X@ s>�(�。'fa�

1 个答案:

答案 0 :(得分:2)

这是因为PHP包返回字符串,其中javascript缓冲区返回Array。

这个答案可能有所帮助:https://stackoverflow.com/a/41962257/3086531