PHP 8.4.24 Released!

Voting

: max(three, seven)?
(Example: nine)

The Note You're Voting On

Michael
13 years ago
Please be careful when comparing hashes. In certain cases, information can be leaked by using a timing attack. It takes advantage of the == operator only comparing until it finds a difference in the two strings. To prevent it, you have two options.

Option 1: hash both hashed strings first - this doesn't stop the timing difference, but it makes the information useless.

<?php
    if (md5($hashed_value) === md5($hashed_expected)) {
        echo "hashes match!";
    }
?>

Option 2: always compare the whole string.

<?php
    if (hash_compare($hashed_value, $hashed_expected)) {
        echo "hashes match!";
    }

    function hash_compare($a, $b) {
        if (!is_string($a) || !is_string($b)) {
            return false;
        }
        
        $len = strlen($a);
        if ($len !== strlen($b)) {
            return false;
        }

        $status = 0;
        for ($i = 0; $i < $len; $i++) {
            $status |= ord($a[$i]) ^ ord($b[$i]);
        }
        return $status === 0;
    }
?>

<< Back to user notes page

To Top