(PHP 5 >= 5.6.0, PHP 7)
hash_equals — Timing attack safe string comparison
$known_string
, string $user_string
) : boolCompares two strings using the same time whether they're equal or not.
This function should be used to mitigate timing attacks; for instance, when testing crypt() password hashes.
known_stringThe string of known length to compare against
user_stringThe user-supplied string
Returns TRUE when the two strings are equal, FALSE otherwise.
Emits an E_WARNING message when either of the
supplied parameters is not a string.
Exemplo #1 hash_equals() 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));
var_dump(hash_equals($expected, $incorrect));
?>
O exemplo acima irá imprimir:
bool(true) bool(false)
Nota:
Both arguments must be of the same length to be compared successfully. When arguments of differing length are supplied,
FALSEis returned immediately and the length of the known string may be leaked in case of a timing attack.
Nota:
It is important to provide the user-supplied string as the second parameter, rather than the first.