Calculate a raw-body keyed HMAC and compare it with the provider signature in constant time. The examples separate the essential operation from the conditions a production implementation must enforce.
What It Does
Calculate a raw-body keyed HMAC and compare it with the provider signature in constant time.
Prerequisites
Use a dedicated development environment with test accounts and records. Separate authorization, validation and error handling from response formatting; never copy demonstration-only secrets into production.
Example 1: Core Behavior
This scenario applies the exact rule described in the guide, with controlled sample values.
<?php
$payload="sample bytes"; $secret="local-test-key"; $header="sha256=".hash_hmac("sha256",$payload,$secret);
$hex=substr($header,7); echo hash_equals(hash_hmac("sha256",$payload,$secret),$hex)?"Valid":"Invalid";
Example 2: Alternative or Failure Case
This scenario applies the exact rule described in the guide, with controlled sample values.
<?php
$body="a=1&b=2"; $signature=hash_hmac("sha256",$body,"key");
$changed="a=2&b=2"; echo hash_equals(hash_hmac("sha256",$changed,"key"),$signature)?"Bad":"Change detected";
Practical Example: Applying the Rule
This scenario applies the exact rule described in the guide, with controlled sample values.
<?php
$header="sha256=not-hex"; $candidate=substr($header,7);
if (!preg_match("/^[a-f0-9]{64}$/D",$candidate)) { echo "Malformed signature rejected"; }
Important Behavior and Edge Cases
Validate signature encoding, use the provider's exact signing format and reject malformed headers.
Comparison with Related Functions or Patterns
| Approach | When it differs |
|---|---|
| Verifying Webhook Signatures | Calculate a raw-body keyed HMAC and compare it with the provider signature in constant time. |
| Related API or pattern | hash_equals prevents ordinary string comparison timing leaks. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Verifying re-serialized JSON instead of the original payload bytes | Validate signature encoding, use the provider's exact signing format and reject malformed headers. |
| Substituting a related API without checking its semantics | hash_equals prevents ordinary string comparison timing leaks. |
Key Takeaways
- Calculate a raw-body keyed HMAC and compare it with the provider signature in constant time.
- Validate signature encoding, use the provider's exact signing format and reject malformed headers.
- hash_equals prevents ordinary string comparison timing leaks.
Select this API or pattern based on its documented behavior and the trust boundaries in your own application, and test all external integrations against their actual deployments.