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?