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.
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)Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.