Skip to content

Commit 03bd74b

Browse files
committed
[Security] Use hash_equals for constant-time string comparison
1 parent b554961 commit 03bd74b

File tree

1 file changed

+9
-1
lines changed

1 file changed

+9
-1
lines changed

src/Symfony/Component/Security/Core/Util/StringUtils.php

+9-1
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ private function __construct() {}
2727
* Compares two strings.
2828
*
2929
* This method implements a constant-time algorithm to compare strings.
30+
* Regardless of the used implementation, it will leak length information.
3031
*
3132
* @param string $knownString The string of known length to compare against
3233
* @param string $userInput The string that the user can control
@@ -35,6 +36,13 @@ private function __construct() {}
3536
*/
3637
public static function equals($knownString, $userInput)
3738
{
39+
$knownString = (string) $knownString;
40+
$userInput = (string) $userInput;
41+
42+
if (function_exists('hash_equals')) {
43+
return hash_equals($knownString, $userInput);
44+
}
45+
3846
$knownLen = strlen($knownString);
3947
$userLen = strlen($userInput);
4048

@@ -45,7 +53,7 @@ public static function equals($knownString, $userInput)
4553
$result = $knownLen - $userLen;
4654

4755
// Note that we ALWAYS iterate over the user-supplied length
48-
// This is to prevent leaking length information
56+
// This is to mitigate leaking length information
4957
for ($i = 0; $i < $userLen; $i++) {
5058
$result |= (ord($knownString[$i]) ^ ord($userInput[$i]));
5159
}

0 commit comments

Comments
 (0)