diff options
Diffstat (limited to 'Core/Util/StringUtils.php')
-rw-r--r-- | Core/Util/StringUtils.php | 26 |
1 files changed, 16 insertions, 10 deletions
diff --git a/Core/Util/StringUtils.php b/Core/Util/StringUtils.php index 2e8925d..01441cb 100644 --- a/Core/Util/StringUtils.php +++ b/Core/Util/StringUtils.php @@ -21,37 +21,43 @@ class StringUtils /** * This class should not be instantiated */ - private function __construct() {} + private function __construct() + { + } /** * Compares two strings. * * This method implements a constant-time algorithm to compare strings. + * Regardless of the used implementation, it will leak length information. * * @param string $knownString The string of known length to compare against * @param string $userInput The string that the user can control * - * @return Boolean true if the two strings are the same, false otherwise + * @return bool true if the two strings are the same, false otherwise */ public static function equals($knownString, $userInput) { - // Prevent issues if string length is 0 - $knownString .= chr(0); - $userInput .= chr(0); + $knownString = (string) $knownString; + $userInput = (string) $userInput; + + if (function_exists('hash_equals')) { + return hash_equals($knownString, $userInput); + } $knownLen = strlen($knownString); $userLen = strlen($userInput); + // Extend the known string to avoid uninitialized string offsets + $knownString .= $userInput; + // Set the result to the difference between the lengths $result = $knownLen - $userLen; // Note that we ALWAYS iterate over the user-supplied length - // This is to prevent leaking length information + // This is to mitigate leaking length information for ($i = 0; $i < $userLen; $i++) { - // Using % here is a trick to prevent notices - // It's safe, since if the lengths are different - // $result is already non-0 - $result |= (ord($knownString[$i % $knownLen]) ^ ord($userInput[$i])); + $result |= (ord($knownString[$i]) ^ ord($userInput[$i])); } // They are only identical strings if $result is exactly 0... |