diff --git a/src/Symfony/Component/Security/Core/Util/StringUtils.php b/src/Symfony/Component/Security/Core/Util/StringUtils.php index e8f3e3bb64b9..861e94cb349f 100644 --- a/src/Symfony/Component/Security/Core/Util/StringUtils.php +++ b/src/Symfony/Component/Security/Core/Util/StringUtils.php @@ -45,8 +45,8 @@ public static function equals($knownString, $userInput) return hash_equals($knownString, $userInput); } - $knownLen = strlen($knownString); - $userLen = strlen($userInput); + $knownLen = self::safeStrlen($knownString); + $userLen = self::safeStrlen($userInput); // Extend the known string to avoid uninitialized string offsets $knownString .= $userInput; @@ -63,4 +63,26 @@ public static function equals($knownString, $userInput) // They are only identical strings if $result is exactly 0... return 0 === $result; } + + /** + * Return the number of bytes in a string + * + * @param string $string The string whose length we wish to obtain + * @return int + */ + public static function safeStrlen($string) + { + // Premature optimization + // Since this cannot be changed at runtime, we can cache it + static $func_exists = null; + if ($func_exists === null) { + $func_exists = function_exists('mb_strlen'); + } + + if ($func_exists) { + return mb_strlen($string, '8bit'); + } + + return strlen($string); + } }