Skip to content
GreenSnippets

Verify an HMAC signature in PHP (constant time)

Check a webhook or signed-request HMAC with hash_hmac and hash_equals to avoid timing attacks.

PHP
<?php
function verifySignature(string $rawBody, string $signatureHex, string $secret): bool
{
    $expected = hash_hmac('sha256', $rawBody, $secret);
    return hash_equals($expected, strtolower($signatureHex));
}

How it works

Compute the HMAC over the raw request body (not re-encoded JSON) with your shared secret, then compare with hash_equals, which takes the same time regardless of where the strings differ. Plain === can leak information through timing.

Also check a timestamp inside the signed payload and reject old requests to limit replay attacks. Read the raw body with file_get_contents('php://input').