我在 Windows 上运行 Node.js 和 php,并使用 Node.js 中包含的加密模块。
\n\nPHP脚本:
\n\nhash_hmac("sha256", "foo", "bar", true) // the true enables binary output\nRun Code Online (Sandbox Code Playgroud)\n\n输出:
\n\n\n\n\n\xc2\xb6y3!\xc3\xa8\xc2\xac\xe2\x95\x9d\xe2\x99\x82\xc3\xaf\xe2\x96\xba\xc3\xb3\xe2\x94\x82\xc3\x91\ xe2\x94\x9cF\xc3\xa4\xe2\x95\x9a\xe2\x94\x98CA\xe2\x95\x9d\xc2\xb1G6\xe2\x96\x84rp\xc2\xb8t\xe2\x86\x91Q
\n
Node.js 脚本:
\n\ncrypto.createHmac("sha256", "bar").update("foo").digest("binary");\nRun Code Online (Sandbox Code Playgroud)\n\n输出:
\n\n\n\n\n\xc2\xb6y3!?\xc2\xaa\xc2\xbc\xe2\x99\x82?\xe2\x96\xba\xc2\xa2\xc2\xb3\xc2\xa5\xc3\x83F?\xc3\x88\xc3 \x99CA\xc2\xbc\xc3\xb1G6\xc3\x9crp\xc3\xb7t\xe2\x86\x91Q
\n
我还想知道为什么有些数字相同而有些则不同。
\n\n我还尝试获取十六进制而不是二进制结果,它们都输出相同的.
\n\nhash_hmac("sha256", "foo", "bar", false); // false outputs hex data\ncrypto.createHmac("sha256", "bar").update("foo").digest("hex"); // notice "hex"\nRun Code Online (Sandbox Code Playgroud)\n\n这不是解决方案,因为我未能将十六进制数据转换为二进制:
\n\nvar hmac = crypto.createHmac("sha256", "bar").update("foo").digest("hex");\nvar binary = new Buffer(hmac, "hex");\nRun Code Online (Sandbox Code Playgroud)\n\n变量binary输出:
\n\n\xc2\xb6y3!???\xe2\x99\x82?\xe2\x96\xba??????F???CA??G6?rp?t\xe2\x86\x91Q
\n
我在为 OTP simplepay 实现 Node js 解决方案时遇到了同样的问题。
\n\nPHP代码:
\n\nbase64_encode(hash_hmac(\'SHA384\', $text, trim($key), true));\nRun Code Online (Sandbox Code Playgroud)\n\nJS代码:
\n\nfunction get_hash(key, text) {\n const crypto = require("crypto");\n const algorithm = "sha384";\n\n var hmac = crypto.createHmac(algorithm, key).update(text);\n return hmac.digest().toString(\'base64\');\n}\nRun Code Online (Sandbox Code Playgroud)\n\n因此,两者都注销/回显 - 给出相同的结果。\n在您的情况下,二进制输出将是:
\n\ncrypto.createHmac("sha256", "bar").update("foo").digest().toString(\'binary\');\nRun Code Online (Sandbox Code Playgroud)\n\n但是,请记住,由于字符编码的原因,记录和回显二进制字符串将给出略有不同的视图。您可以看到相同的字符,但也可以看到不同的字符。
\n\nPHP回显
\n\n\n\n\n,cAW\'B\xef\xbf\xbd\xef\xbf\xbdo\xef\xbf\xbd\xef\xbf\xbd\xe5\x82\xb1\xef\xbf\xbd@\xef\xbf\xbdVl\xce \xacf\xef\xbf\xbdR@y\xef\xbf\xbd,?0\xef\xbf\xbd^1=Y\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\xef\ xbf\xbd\xef\xbf\xbdu2
\n
和
\n\n节点控制台.log
\n\n\n\n\n,cAW\'B\xc3\x9b\xc3\xa5o\xc2\xba\xc2\xb0\xc3\xa5\xc2\xb1\xc2\xb9@Vl\xc3\x8e\xc2\xacf\xc3\x9e\xc3\ xaa\xc2\xa7\xc2\xb8\xc2\xa7u2
\n
实际上是一样的,只是看起来不同。\n请参阅此 github 问题和 addaleax\'s 评论
\n| 归档时间: |
|
| 查看次数: |
1603 次 |
| 最近记录: |