PHP中哈希函数的恒定时间比较

I am trying to verify whether a string matches a SHA-512 (Unix) hash ($6$..) in PHP. Much like the password_verify() function for Blowfish (BCrypt) but for SHA-512 (Unix) instead.

I stumbled upon hash_equals which tends to compare two strings using the same time. However, I am unable to get the expected output boolean true on the following:

<?php

$expected  = '$6$9e87b0c78da9ab83$5V16BLuWUkoG3g1oH3kwhs8rzBpjydUps1qBXuY3PkkFzDSjqklT47L5pmG8JPqDRDk.ZTJoS/ogtHkyXC2L40';

if (CRYPT_SHA512 == 1) {
    $correct = crypt('OkvraMADvua', '$6$12$usesomesillystringforsalt$');
}

var_dump(hash_equals($expected, $correct));

?>

Right now, I get boolean false even though the hash value of $expected corresponds to the plaintext and the hash generated for the $correct variable also matches that same plaintext (OkvraMADvua).

  • The issue is that the salt is always different and that is to be expected with crypt(3) algorithms. Whenever I use the same salt, it's evident that the output would be boolean true.