Md. Yusuf Md. Yusuf - 23 days ago 14
PHP Question

Difference between hash_equals and strcmp fucntion

hash_equals — Timing attack safe string comparison.
I wonder what is timing attack safe.

I see the implementation of hash_equals

$result = 0;
for ($i = 0; $i < $len; $i++) {
$result |= (ord($known_string[$i]) ^ ord($user_string[$i]));
}
// They are only identical strings if $result is exactly 0...
return 0 === $result;


I want to know where is the time comparison.

Answer

Normally, a string comparison (strcmp or ==) breaks on a first non-matching char, so if your password is 12345 and the attacker provides 9xxxx and then 1xxxx, she can measure the time difference between two comparisons and deduce that the second string is more correct (since the second comparison took more time). hash_equals eliminates this type of attack by always comparing all characters of both strings, not matter if they match or not. So more and less correct strings will take the same time.

Comments