Home > Software design >  Generate a hashed message with SHA256 hmac in php (key & msg are fake)
Generate a hashed message with SHA256 hmac in php (key & msg are fake)

Time:11-09

I'm using php 8.0.11, i have to generate a SHA256 encrypted messagesignature.When i test the API in postman with javascipt code in Pre-request script it give the right encrypted messagesignature, i converted the script to php when i test it in php it sends a different wrong encrypted messagesignature (key & msg are fake) :

javascript code (Pre-request script in postman):

      let msg='mymessage'
      const hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256,"myapipkey");
      hmac.update(msg);
      const messageSignature = hmac.finalize().toString();
      pm.globals.set("messageSignature",messageSignature);
      console.log('messageSi:',pm.globals.get('messageSignature'))

````
php code:
````php

    $data_to_hash = "mymessage";
    $data_hmac=hash('sha256',  $data_to_hash);
    $ctx = hash_init('sha256', HASH_HMAC, 'myapipkey');
    hash_update($ctx, $data_hmac);
    $result = hash_final($ctx);
    echo $result;

````

CodePudding user response:

A simple change to the PHP code should give the correct result.

It looks like you were hashing twice (or something like that!)

$data_to_hash = "mymessage";
$ctx = hash_init('sha256', HASH_HMAC, 'myapipkey');
hash_update($ctx, $data_to_hash);
$result = hash_final($ctx);
echo $result;

In any case, the output of the above code will be:

898786a1fa80da9b463c1c7c9045377451c40cf3684cbba73bdfee48cd3a5b8f

Which is the same as the JavaScript code, both match the output given here:

https://codebeautify.org/hmac-generator

With Algorithm = 'SHA256', Key = 'myapipkey' and Plaintext = 'mymessage'.

  • Related