What is the best way to compare hashed strings? (Php)

Should I use if(strcmp(md5($string),$hash)==0) or if(md5($string)==$hash)

+6
string comparison php
source share
6 answers

== been shown by other users here to be extremely unreliable. Instead, use strcmp() .

The third option, if you really want to use the comparison operator, is to use === , which does not perform type coercion of any type and therefore saves types and values โ€‹โ€‹for comparison purposes.

0
source share

You must be very careful when comparing hashes directly for things like authentication, as you can open a window for a temporary attack .

Although this sounds very inconsistent, you should completely compare the string, avoiding any optimizations (for example, exit early if the character is different).

Here are some links about the problem:

And here are some ideas to fix this:

+20
source share

If you are comparing strings, use strcmp or === . People prefer === because strcmp can be confusing (it returns 0 if successful, wat).

You should use === , not == . == converts both operands to integers, if they can be interpreted as such, and since the MD5 hash does not fit into an integer, they will be truncated around half. Therefore, only the first half of the hashes should be equal. See http://phpsadness.com/sad/47 .

If you have hashed passwords, consider using a slow and strong hashing algorithm such as PBKDF2 rather than MD5.

+15
source share

If you are using anything newer than PHP 5.6 (and including), you should use the function of protection against accidental string binding .

 if (hash_equals($expected, $correct)) { } 

(If you are using PHP 5.5 or earlier, see here for equivalents .)

+2
source share

In fact, you should use password_verify for this, and use all other password_* functions. They are available in PHP> = 5.5.0.

You can use this polyfill as a backup. It currently works with PHP> = 5.3.7.

And if you really can't / don't want to use this, then hash_equals (and polyfill for this) is like @MM. already said.

0
source share

I think if(md5($string) == $hash) better because you only have one comparison instead of 2 (stcmp and ==).

md5 only generates ascii characters that do not need binary safe comparisons.

-4
source share

All Articles