<?php
function hmac_compare(string $a, string $b): bool
{
$random = random_bytes(32);
return hash_hmac('sha256', $a, $random) === hash_hmac('sha256', $b, $random);
}
$key = random_bytes(32);
$x = hash_hmac('sha256', 'test', $key);
$y = hash_hmac('sha256', 'test', $key);
$z = hash_hmac('sha256', 'test2', $key);
var_dump(
hmac_compare($x, $y), // true
hmac_compare($y, $z)
);
- Output for 7.2.0 - 7.2.34, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.28, 8.1.0 - 8.1.18, 8.2.0 - 8.2.5
- bool(true)
bool(false)
preferences:
34.25 ms | 406 KiB | 5 Q