PHP Function Reference

PHP hash_equals() Function



The PHP hash_equals() function compares two strings using the same time whether they are equal or not. This function is used to mitigate timing attacks, for example - when testing crypt() password hashes.

Syntax

hash_equals(known_string, user_string)

Parameters

known_string Required. Specify the string of known length to compare against.
user_string Required. Specify the user-supplied string.

Return Value

Returns true when the two strings are equal, false otherwise.

Exceptions

Emits an E_WARNING message when either of the supplied parameters is not a string.

Example: hash_equals() example

The example below shows the usage of hash_equals() function.

<?php
//12 character salt starting with $1$
$known_string  = crypt('CorrectPassword', '$1$mypasswo$');
$correct   = crypt('CorrectPassword', '$1$mypasswo$');
$incorrect = crypt('WrongPassword', '$1$mypasswo$');

//comparing strings and displaying the result
var_dump(hash_equals($known_string, $correct));
var_dump(hash_equals($known_string, $incorrect));
?>

The output of the above code will be:

bool(true)
bool(false)

❮ PHP Hash Reference