Skip to content

[Security] Use hash_equals for constant-time string comparison (again) #11822

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 10, 2014
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
[Security] Use hash_equals for constant-time string comparison
  • Loading branch information
dunglas committed Sep 4, 2014
commit 03bd74bdeae5e686cb15e6ec2b3b629f58211419
10 changes: 9 additions & 1 deletion src/Symfony/Component/Security/Core/Util/StringUtils.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ 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
Expand All @@ -35,6 +36,13 @@ private function __construct() {}
*/
public static function equals($knownString, $userInput)
{
$knownString = (string) $knownString;
$userInput = (string) $userInput;

if (function_exists('hash_equals')) {
return hash_equals($knownString, $userInput);
}

$knownLen = strlen($knownString);
$userLen = strlen($userInput);

Expand All @@ -45,7 +53,7 @@ public static function equals($knownString, $userInput)
$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++) {
$result |= (ord($knownString[$i]) ^ ord($userInput[$i]));
}
Expand Down