Skip to content
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

Use timing-safe hash comparision #20

Merged
merged 1 commit into from
Sep 5, 2016
Merged
Changes from all commits
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
40 changes: 39 additions & 1 deletion src/Encryption/Symmetric.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,44 @@ public function encrypt($value)
*/
public function verify($value, $signature)
{
return $this->algorithm->compute($value) === $signature;
$computedValue = $this->algorithm->compute($value);

return $this->timingSafeEquals($signature, $computedValue);
}

/**
* A timing safe equals comparison.
*
* @see http://blog.ircmaxell.com/2014/11/its-all-about-time.html
*
* @param string $safe The internal (safe) value to be checked
* @param string $user The user submitted (unsafe) value
*
* @return boolean True if the two strings are identical.
*/
public function timingSafeEquals($safe, $user)
{
if (function_exists('hash_equals')) {
return hash_equals($user, $safe);
}

$safeLen = strlen($safe);
$userLen = strlen($user);

/*
* In general, it's not possible to prevent length leaks. So it's OK to leak the length.
* @see http://security.stackexchange.com/questions/49849/timing-safe-string-comparison-avoiding-length-leak
*/
if ($userLen != $safeLen) {
return false;
}

$result = 0;

for ($i = 0; $i < $userLen; $i++) {
$result |= (ord($safe[$i]) ^ ord($user[$i]));
}

return $result === 0;
}
}