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.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
hash_equals() – Constant‑Time String Comparison to Prevent Timing Attacks

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)
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

securityPHPstring-comparisonhash_equalstiming attack
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.