note 111435 modified in function.hash-hmac by danbrown

From: Date: Mon, 04 Mar 2013 18:02:03 +0000
Subject: note 111435 modified in function.hash-hmac by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-193870@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; } $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; } ?> --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

« previous php.notes (#193870) next »