3

In JavaScript (NodeJS), I'm trying to validate a payload's origin with HMAC signature made using PHP process of:

$raw_json = '{"link":"https://data.com.sg/resource?2f6b5c55-c8cb-4398-875c-a1c69e0d2706"}';  
$payload = json_decode($raw_json, true);  
$signature = hash_hmac('sha256', json_encode($payload), 'SECRET_KEY');

using similar JS process of:

const rawJSON = '{"link":"https://data.com.sg/resource?2f6b5c55-c8cb-4398-875c-a1c69e0d2706"}';
const payload = JSON.parse(rawJSON)
const signature = HMACSHA256(JSON.stringify(payload), 'SECRET_KEY');

But I found that the length of JSON.stringify(payload) and json_encode($payload) is different. Logging both data, I found that that is an issue in escaped character resulted when doing json_encode on string with link or / character (or maybe any other).

JavaScript's JSON.stringify results

{"link":"https://data.com.sg/resource?2f6b5c55-c8cb-4398-875c-a1c69e0d2706"}

PHP's json_encode results

{"link":"https:\/\/data.com.sg\/resource?2f6b5c55-c8cb-4398-875c-a1c69e0d2706"}

I cannot change the process in PHP system side. So I gotta adapt the HMAC generation process in the nodejs system side.

What can be done so I could reproduce json_encode in JavaScript flawlessly?

Pls see P.S.


P.S.

I've tried using some json_encode module but it's still giving me the same result as JSON.stringify.

For now I'm tackling it by adding replacer talked here. But as my payload will be full of formatted text, I'm concerned with the possibility of another case of result differences due to characters existence other than / char. Or should I be not concerned about that?

shrotavre
  • 98
  • 6
  • 2
    You might find this interesting ~ [json_encode() escaping forward slashes](https://stackoverflow.com/q/10210338/283366). In my opinion, PHP is a little over-zealous with its defaults. – Phil Apr 09 '18 at 05:18
  • no, I don't have access to edit the signature generation process in PHP system @Phil – shrotavre Apr 09 '18 at 05:22
  • 1
    Damn, that's unfortunate. I think you're stuck with the replacer then. Consult the PHP documentation to see what else `json_encode()` does by default – Phil Apr 09 '18 at 05:24
  • In PHP you can use `JSON_UNESCAPED_SLASHES` flag and it won't add forward slashes – 4EACH Apr 09 '18 at 06:09

0 Answers0