Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/42.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
NodeJS从HMAC返回除php之外的其他二进制结果_Php_Node.js_Hmac - Fatal编程技术网

NodeJS从HMAC返回除php之外的其他二进制结果

NodeJS从HMAC返回除php之外的其他二进制结果,php,node.js,hmac,Php,Node.js,Hmac,我在windows上运行node.js和php,并使用node.js中包含的加密模块 Php脚本: hash_hmac("sha256", "foo", "bar", true) // the true enables binary output 产出: ^y3!è¬╝♂ï►ó│Ñ├Fä╚┘加利福尼亚州╝±G6▄rp¸t↑Q Node.js脚本: crypto.createHmac("sha256", "bar").update("foo").digest("binary"); 产出: ^y

我在windows上运行node.js和php,并使用node.js中包含的加密模块

Php脚本:

hash_hmac("sha256", "foo", "bar", true) // the true enables binary output
产出:

^y3!è¬╝♂ï►ó│Ñ├Fä╚┘加利福尼亚州╝±G6▄rp¸t↑Q

Node.js脚本:

crypto.createHmac("sha256", "bar").update("foo").digest("binary");
产出:

^y3!?ª¼♂?►第三¥F?CA¼ñG6Ürp÷t↑Q

我还想知道为什么有些数字是相同的,而有些则不同


我还尝试获取十六进制而不是二进制结果,它们都输出相同的

hash_hmac("sha256", "foo", "bar", false); // false outputs hex data
crypto.createHmac("sha256", "bar").update("foo").digest("hex"); // notice "hex"
这不是一个解决方案,因为我未能将十六进制数据转换为二进制:

var hmac = crypto.createHmac("sha256", "bar").update("foo").digest("hex");
var binary = new Buffer(hmac, "hex");
变量
二进制
输出:

^y3!???♂?►????F???CA???G6?rp?t↑Q


我在为OTP simplepay实现node js解决方案时遇到了同样的问题

PHP代码:

base64_encode(hash_hmac('SHA384', $text, trim($key), true));
JS代码:

function get_hash(key, text) {
    const crypto = require("crypto");
    const algorithm = "sha384";

    var hmac = crypto.createHmac(algorithm, key).update(text);
    return hmac.digest().toString('base64');
}
因此,两个注销/回显-给出相同的结果。 在您的情况下,二进制输出将是:

crypto.createHmac("sha256", "bar").update("foo").digest().toString('binary');
但是,请记住,由于字符编码的原因,记录和回显二进制字符串将给出稍微不同的视图。您可以看到相同的字符,但也可以看到不同的字符

PHP回声

,呱呱��o��傱�@�Vlάf�R@y�,?0�^1=Y�����u2

NODE console.log

,cAW'BÛåoºå±@VlÎfååååu2

实际上是一样的,只是看起来不同而已。
请参见

只要您在二进制数据和字符串之间进行转换,您就可以使用。实际的二进制数据在两者之间是相同的,通过十六进制输出进行验证,但打印时用于表示它们的字符编码不是。我猜PHP假设节点的缓冲区将使用@JonathanLonowski使它们保持一致?请不要只发布代码作为答案,还要解释代码的作用以及它如何解决问题。带有解释的答案通常更有帮助,质量更好,更容易吸引选票。
calculateHmac(payload) {
    const hmac = crypto.createHmac('sha256', KEY);
    hmac.update(Buffer.from(payload).toString());
    let bin = hmac.digest();
    return Buffer.from(bin).toString('base64');
}