HMAC (Hash-based Message Authentication Code)
debt(d5/e3/b3/t7)
Closest to 'specialist tool catches it' (d5). The detection_hints list semgrep and psalm, both specialist/SAST tools. The code_pattern shows they can catch the naive hash($secret.$message) pattern, but the timing-oracle mistake (using === instead of hash_equals()) also requires a specialist SAST rule rather than a default linter, so d5 is the right anchor.
Closest to 'simple parameterised fix' (e3). The quick_fix is a direct function swap: replace hash('sha256', ...) with hash_hmac('sha256', $message, $secret) and replace == with hash_equals(). Each fix is a small, localised change — typically one or two call sites per file — but may need to be applied in several places across the codebase, placing it slightly above a pure one-liner (e1) but not requiring significant refactor.
Closest to 'localised tax' (b3). HMAC usage is typically scoped to specific signing/verification points (webhook handlers, API token validation, etc.). While it applies across web, cli, and queue-worker contexts, the actual code surface is limited to dedicated auth/integrity functions rather than permeating every layer of the codebase.
Closest to 'serious trap' (t7). The misconception field calls out that == comparison appears safe to a competent developer — equality comparison is the standard idiom for string checks in PHP — but it actually introduces a timing oracle. This directly contradicts normal string-comparison intuition and is a well-documented but easily missed gotcha. The naive hash concatenation mistake also contradicts how developers expect a keyed hash to work, reinforcing the t7 score.
Also Known As
TL;DR
Explanation
HMAC (RFC 2104) combines a cryptographic hash function with a secret key: HMAC(key, message) = H((key XOR opad) || H((key XOR ipad) || message)). Unlike a plain hash, a valid HMAC cannot be forged without the key. In PHP, use hash_hmac('sha256', $message, $secretKey) and verify with hash_equals() to prevent timing attacks. Common uses include API request signing, webhook payload verification, signed cookies, and password-reset token authentication. Choose SHA-256 or SHA-512 — avoid MD5 or SHA-1.
Common Misconception
Why It Matters
Common Mistakes
- Using hash('sha256', $secret . $data) instead of hash_hmac() — this is vulnerable to length-extension attacks.
- Comparing HMACs with === instead of hash_equals(), introducing a timing oracle.
- Using a weak or short key — HMAC security is bounded by the key entropy.
- Reusing the same key for different purposes — a key used for HMAC should not also be used for encryption.
Code Examples
if (md5($payload) === $receivedHash) { /* forgeable — no key */ }
if (hash_equals(hash_hmac('sha256', $payload, $secret), $receivedHash)) { /* keyed, constant-time */ }