hash_equals() – Constant‑Time String Comparison to Prevent Timing Attacks
The article explains PHP's hash_equals() function, which performs a constant‑time comparison of two strings to mitigate timing attacks, describes its parameters and return value, and provides example code demonstrating correct and incorrect usage with crypt() hashes.
Reading font
hash_equals() compares two strings in constant time, making the execution time independent of the strings' contents, which helps prevent timing attacks. It is especially useful when comparing password hashes generated by crypt().
Parameters
known_string : the known string of a fixed length to be compared.
user_string : the string supplied by the user.
Return value : true if the strings are identical, otherwise false.
Example
<?php
$expected = crypt('12345', '$2a$07$usesomesillystringforsalt$');
$correct = crypt('12345', '$2a$07$usesomesillystringforsalt$');
$incorrect = crypt('apple', '$2a$07$usesomesillystringforsalt$');
var_dump(hash_equals($expected, $correct)); // bool(true)
var_dump(hash_equals($expected, $incorrect)); // bool(false)
?>Output
bool(true)
bool(false)For questions about attribution, corrections or content rights, please contactand we will review it promptly.