Skip to content
This repository has been archived by the owner on Jul 28, 2022. It is now read-only.

Commit

Permalink
Constant time comparison for codes
Browse files Browse the repository at this point in the history
  • Loading branch information
lstrojny authored and jordisala1991 committed Mar 17, 2018
1 parent 789fd1c commit f4f4be1
Showing 1 changed file with 6 additions and 10 deletions.
16 changes: 6 additions & 10 deletions src/GoogleAuthenticator.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,24 +78,20 @@ public function __construct(int $passCodeLength = 6, int $secretLength = 10, \Da
*/
public function checkCode($secret, $code): bool
{
$result = 0;

// current period
if (hash_equals($this->getCode($secret, $this->now), $code)) {
return true;
}
$result += hash_equals($this->getCode($secret, $this->now), $code);

// previous period, happens if the user was slow to enter or it just crossed over
$dateTime = new \DateTimeImmutable('@'.($this->now->getTimestamp() - $this->codePeriod));
if (hash_equals($this->getCode($secret, $dateTime), $code)) {
return true;
}
$result += hash_equals($this->getCode($secret, $dateTime), $code);

// next period, happens if the user is not completely synced and possibly a few seconds ahead
$dateTime = new \DateTimeImmutable('@'.($this->now->getTimestamp() + $this->codePeriod));
if (hash_equals($this->getCode($secret, $dateTime), $code)) {
return true;
}
$result += hash_equals($this->getCode($secret, $dateTime), $code);

return false;
return $result > 0;
}

/**
Expand Down

0 comments on commit f4f4be1

Please sign in to comment.