1.2.199. Compare Hash¶
When comparing hash values, it is important to use the strict comparison : hash_equals(),
===
or!==
.
In a number of situations, the hash value will start with 0e
, and PHP will understand that the comparison involves integers : it will then convert the strings into numbers, and it may end up converting them to 0.
Here is an example : You may also use password_hash() and password_verify() : they work together without integer conversion problems, and they can’t be confused with a number.
<?php
// The two following passwords hashes matches, while they are not the same.
$hashed_password = 0e462097431906509000000000000;
if (hash('md5','240610708',false) == $hashed_password) {
print 'Matched.'.PHP_EOL;
}
// hash returns a string, that is mistaken with 0 by PHP
// The strength of the hashing algorithm is not a problem
if (hash('ripemd160','20583002034',false) == '0') {
print 'Matched.'.PHP_EOL;
}
if (hash('md5','240610708',false) !== $hashed_password) {
print 'NOT Matched.'.PHP_EOL;
}
// Display true
var_dump(md5('240610708') == md5('QNKCDZO') );
?>
See also Magic Hashes , What is the best way to compare hashed strings? (PHP) and md5(‘240610708’) == md5(‘QNKCDZO’).
1.2.199.1. Suggestions¶
Use dedicated functions for hash comparisons
Use identity operators (===), and not equality operators (==) to compare hashes
Compare hashes in the database (or external system), where such confusion is not possible
1.2.199.2. Specs¶
Short name |
Security/CompareHash |
Rulesets |
|
Exakat since |
0.8.4 |
PHP Version |
All |
Severity |
Major |
Time To Fix |
Quick (30 mins) |
Precision |
Very high |
Features |
cryptography, hash |
ClearPHP |
|
Examples |
|
Available in |