简体   繁体   中英

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. 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!

If you match what you do in PHP with base64_decode , you get the correct value:

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

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. If you provide the same inputs, both libraries will give you the same output value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM