Made optimization deprecating modulus operator

This commit is contained in:
Yosmany Garcia 2014-08-05 20:01:06 -04:00
parent 678f7728eb
commit 000bd0d863

View File

@ -35,23 +35,19 @@ class StringUtils
*/ */
public static function equals($knownString, $userInput) public static function equals($knownString, $userInput)
{ {
// Prevent issues if string length is 0
$knownString .= chr(0);
$userInput .= chr(0);
$knownLen = strlen($knownString); $knownLen = strlen($knownString);
$userLen = strlen($userInput); $userLen = strlen($userInput);
// Extend know string to avoid uninitialized string offsets
$knownString .= $userInput;
// Set the result to the difference between the lengths // Set the result to the difference between the lengths
$result = $knownLen - $userLen; $result = $knownLen - $userLen;
// Note that we ALWAYS iterate over the user-supplied length // Note that we ALWAYS iterate over the user-supplied length
// This is to prevent leaking length information // This is to prevent leaking length information
for ($i = 0; $i < $userLen; $i++) { for ($i = 0; $i < $userLen; $i++) {
// Using % here is a trick to prevent notices $result |= (ord($knownString[$i]) ^ ord($userInput[$i]));
// It's safe, since if the lengths are different
// $result is already non-0
$result |= (ord($knownString[$i % $knownLen]) ^ ord($userInput[$i]));
} }
// They are only identical strings if $result is exactly 0... // They are only identical strings if $result is exactly 0...