Change behavior to mirror hash_equals() returning early if there is a length mismatch
This commit is contained in:
parent
8269589c91
commit
45cfb44df8
@ -38,10 +38,6 @@ class StringUtils
|
|||||||
*/
|
*/
|
||||||
public static function equals($knownString, $userInput)
|
public static function equals($knownString, $userInput)
|
||||||
{
|
{
|
||||||
if (function_exists('hash_equals')) {
|
|
||||||
return hash_equals($knownString, $userInput);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Avoid making unnecessary duplications of secret data
|
// Avoid making unnecessary duplications of secret data
|
||||||
if (!is_string($knownString)) {
|
if (!is_string($knownString)) {
|
||||||
$knownString = (string) $knownString;
|
$knownString = (string) $knownString;
|
||||||
@ -51,16 +47,20 @@ class StringUtils
|
|||||||
$userInput = (string) $userInput;
|
$userInput = (string) $userInput;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (function_exists('hash_equals')) {
|
||||||
|
return hash_equals($knownString, $userInput);
|
||||||
|
}
|
||||||
|
|
||||||
$knownLen = self::safeStrlen($knownString);
|
$knownLen = self::safeStrlen($knownString);
|
||||||
$userLen = self::safeStrlen($userInput);
|
$userLen = self::safeStrlen($userInput);
|
||||||
|
|
||||||
// Set the result to the difference between the lengths
|
if ($userLen != $knownLen) {
|
||||||
$result = $knownLen - $userLen;
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
// Always iterate over the minimum length possible.
|
$result = 0;
|
||||||
$iterationLen = min($knownLen, $userLen);
|
|
||||||
|
|
||||||
for ($i = 0; $i < $iterationLen; $i++) {
|
for ($i = 0; $i < $knownLen; $i++) {
|
||||||
$result |= (ord($knownString[$i]) ^ ord($userInput[$i]));
|
$result |= (ord($knownString[$i]) ^ ord($userInput[$i]));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user