-1

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;

````
albertyaz
  • 39
  • 1
  • 2
  • 11
  • Does this answer your question? [Encrypt with PHP, Decrypt with Javascript (cryptojs)](https://stackoverflow.com/questions/24337317/encrypt-with-php-decrypt-with-javascript-cryptojs) – Nico Haase Nov 08 '21 at 09:32
  • Or this? https://stackoverflow.com/questions/20433467/how-to-get-the-same-result-with-php-and-cryptojs-using-sha256 – Nico Haase Nov 08 '21 at 09:33
  • Or this? https://stackoverflow.com/questions/34941233/why-hmac-sha256-return-different-value-on-php-javascript – Nico Haase Nov 08 '21 at 09:33
  • OR does this answer your question? [Encrypt with CryptoJS and decrypt with PHP](https://stackoverflow.com/questions/29509934/encrypt-with-cryptojs-and-decrypt-with-php) – hassan Nov 08 '21 at 09:34
  • @NicoHaase I think the second and third linked QA make sense, but the first one is about encryption/decryption, not really what the OP asks. – jps Nov 08 '21 at 09:35
  • @hassan why do you suggest a Q/A about AES encryption as a dup target for a question about sha256 hashes? Nico's second and third link make more sense. – jps Nov 08 '21 at 09:38
  • btw. SHA256 is a hashing algorithm, not encryption. – jps Nov 08 '21 at 09:47
  • why did you now revert all the edits that have been made to fix grammar and code formatting errors? – jps Nov 08 '21 at 09:52

1 Answers1

2

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

Terry Lennox
  • 29,471
  • 5
  • 28
  • 40