note 111435 modified in function.hash-hmac by nikic
| From: | nikic@php.net | Date: | Wed, 12 Mar 2014 12:02:47 +0000 |
| Subject: | note 111435 modified in function.hash-hmac by nikic | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-198870@lists.php.net to get a copy of this message | ||
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;
}
?>
--was--
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;
}
$lena = strlen($a);
$lenb = strlen($b);
if ($lena !== $lenb) {
return false;
}
$match = true;
for ($i = 0; $i < $lena; $i++) {
$match = $match && ((ord($a[$i]) ^ ord($b[$i])) === 0);
}
return $match;
}
?>
http://php.net/manual/en/function.hash-hmac.php