首页 > 解决方案 > PHP - 使用十六进制格式的 HMAC 进行 Webhook 身份验证

问题描述

我正在开发与 Onfleet API 一起使用的 PHP Webhook 接收器。对于Webhook 身份验证,它们需要以下内容:

每个 webhook 请求都在 X-Onfleet-Signature 标头中包含来自 Onfleet 的签名。要验证您的 webhook 服务器上收到的 webhook 请求,您需要针对此标头进行验证。要针对 X-Onfleet-Signature 进行验证,您需要将其值与您使用 webhook 机密的十六进制格式生成的 HMAC 和原始字节的 webhook POST 请求的完整主体进行比较。

我从来没有使用过十六进制格式和原始字节等。我的方法是使用类似这样的使用 base64 编码的东西,看看我是否可以适应它,因为它应该非常接近希望:

$myWebhookSecret = 'abc123';

$payload = file_get_contents("php://input");

$yourHash = base64_encode(hash_hmac('sha512', $payload, $myWebhookSecret, true));

$onfleetSignature = $_SERVER['X-Onfleet-Signature'];    

if (hash_equals($onfleetSignature, $yourHash)) {
    $result = 'Success';
    http_response_code(200);
    
} else {
    $result = 'Failure';
    http_response_code(401);
    die;
}

我希望我只需要转换这一行:

$yourHash = base64_encode(hash_hmac('sha512', $payload, $myWebhookSecret, true));

在这里使用十六进制格式,但不确定 PHP 是否可以做到这一点或如何做到这一点?

标签: phpwebhooks

解决方案


这最终对我有用:

$myWebhookSecret = 'abc123';

$payload = file_get_contents("php://input");

$secretInHex = hex2bin($myWebhookSecret);
$yourHash = hash_hmac('sha512', $payload, $secretInHex);

$onfleetSignature = $_SERVER['X-Onfleet-Signature'];    

if (hash_equals($onfleetSignature, $yourHash)) {
    $result = 'Success';
    http_response_code(200);

} else {
    $result = 'Failure';
    http_response_code(401);
    die;
}

推荐阅读