How to use the php:hmac_hash() function in javascript with nodejs package crypto
Im Trying to setup a Webhook in Javascript and have to validate a Header value with my secret
In php it works but in javascript doesn't works (sha256 missmatch)
The PHP Code is following:
$secret = "SUPERSECRETKEY";
//sig header
$headers = getallheaders();
foreach ($headers as $key => $value) {
if (strtolower($key) === 'sig') {
$sig = $value;
}
}
//get the body
$body = file_get_contents('php://input');
//verify the signature
$hash = "sha256=".hash_hmac('sha256', $body, $secret);
if ($hash === $sig) {
http_response_code(200);
} else {
http_response_code(401);
}
and my javascript code is the following:
var secret = "SUPERSECRETKEY";
var sig = req.headers['sig'];
var body = JSON.stringify(req.body);
var hash = "sha256="+ crypto.createHmac('sha256', secret).update(body).digest('hex');
console.log(sig)
console.log(hash)
if (hash === sig) {
res.status(200).send("OK");
} else {
res.status(401).send("Unauthorized");
}
Answer
Solution:
I have added to the app.js(express) following:
app.use(bodyParser.json({
limit: '50mb',
extended: true,
verify: (req, res, buf, encoding) => {
if (buf && buf.length) {
req.rawBody = buf.toString(encoding || 'utf8');
}
},
}));
Source