Reputation: 21
I am trying to match the HMAC in Node.js to the HMAC in PHP for API authorization. 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.
Here is my JS code:
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:
$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!
Upvotes: 0
Views: 275
Reputation: 121
You're base64_decode
ing the secret in PHP but not in Node. Remove the base64_decode
and you get:
gvRZ6BJer/YEkwdJ2OrTetIt1Knza5Vr0ZZ/inV5ySkFW4PBnO77c19L7TFpy9c4FA98/OcK/pB8Gvumwo4CQw==
which matches what I get when testing your JavaScript code.
Upvotes: 2