[英]Why does my crypto.createHmac() generate a different HMAC for the same input?
I am trying to match the HMAC in Node.js to the HMAC in PHP for API authorization. 我正在尝试将Node.js中的HMAC与PHP中的HMAC匹配以进行API授权。 The problem is in Node.js, the createHmac() function generates a different HMAC for the same input, and therefore does not match with the HMAC in PHP.
问题出在Node.js中,createHmac()函数为相同的输入生成不同的HMAC,因此与PHP中的HMAC不匹配。
Here is my JS code: 这是我的JS代码:
events: {
proxyReq: (proxyReq, req) => {
const API_KEY = 125;
const API_SECRET_KEY = 'abc';
let hmac = crypto.createHmac('sha512', API_SECRET_KEY);
hmac.update('0');
const s = hmac.digest('base64');
proxyReq.setHeader('x-api-key', API_KEY);
proxyReq.setHeader('x-api-signature', s);
proxyReq.setHeader('x-api-date', date);
},
PHP: PHP:
$API_SECRET_KEY = 'abc';
$client_signature = $request->header('x-api-signature');
$hmac = base64_encode(hash_hmac('sha512', '0', base64_decode($API_SECRET_KEY), true));
Log::error($client_signature);
Log::error($hmac);
Latest outputs: 最新输出:
[2018-07-11 15:25:28] local.ERROR: dO50o/LcS0/UOXOu/5lHbOMXLe+l225vUU13fWEHeOoUHV7SlcSOE9rQq2UhTlys5N6C4hkq8QTALnpRehtlCg==
[2018-07-11 15:25:28] local.ERROR: 7W2U/3uEKIMD0s39jmZLlJItwTcSSDQdW7WTYdslvIjuUeGydyqwwAuZzaMP0Do5v1zRJxmPITFdy4EHTY5r6A==
[2018-07-11 15:25:33] local.ERROR: UYsXZFyoAB2zELZzwjWyktPEHlYqIP3cgLeb/LXK0X8pnkVxiqEaFWK7c1YIWd6hFPpZHn5j1YdbDhpAL7hQ5A==
[2018-07-11 15:25:33] local.ERROR: 7W2U/3uEKIMD0s39jmZLlJItwTcSSDQdW7WTYdslvIjuUeGydyqwwAuZzaMP0Do5v1zRJxmPITFdy4EHTY5r6A==
Any alternatives or solutions would be appreciated! 任何替代或解决方案将不胜感激!
If you match what you do in PHP with base64_decode
, you get the correct value: 如果将您在PHP中所做的与
base64_decode
相base64_decode
,您将获得正确的值:
const crypto = require('crypto');
const API_SECRET_KEY = Buffer.from('abc', 'base64');
let hmac = crypto.createHmac('sha512', API_SECRET_KEY);
hmac.update('0');
const s = hmac.digest('base64');
console.log(s);
7W2U/3uEKIMD0s39jmZLlJItwTcSSDQdW7WTYdslvIjuUeGydyqwwAuZzaMP0Do5v1zRJxmPITFdy4EHTY5r6A==
https://repl.it/repls/BouncyBogusGigabyte https://repl.it/repls/BouncyBogusGigabyte
Check that you really have the correct constant API_SECRET_KEY value, the correct data input value ('0' in this case), and you are looking at the correct requests in the PHP code. 检查您是否确实具有正确的常数API_SECRET_KEY值,正确的数据输入值(在这种情况下为'0'),以及您是否在PHP代码中查看正确的请求。 If you provide the same inputs, both libraries will give you the same output value.
如果您提供相同的输入,则两个库都将为您提供相同的输出值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.