Skip to content

Checking your reading list…

Retry verification

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

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

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)
About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

Report an issue with this article
securityPHPstring-comparisonhash_equalsTiming Attack

Reader feedback

Was this useful?

Useful0

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion