Psecio\Gatekeeper\Gatekeeper::hash_equals PHP Method

hash_equals() public static method

Safer way to evaluate if hashes equal
public static hash_equals ( string $hash1, string $hash2 ) : boolean
$hash1 string Hash #1
$hash2 string Hash #1
return boolean Pass/fail on hash equality
    public static function hash_equals($hash1, $hash2)
    {
        if (\function_exists('hash_equals')) {
            return \hash_equals($hash1, $hash2);
        }
        if (\strlen($hash1) !== \strlen($hash2)) {
            return false;
        }
        $res = 0;
        $len = \strlen($hash1);
        for ($i = 0; $i < $len; ++$i) {
            $res |= \ord($hash1[$i]) ^ \ord($hash2[$i]);
        }
        return $res === 0;
    }

Usage Example

Example #1
0
 /**
  * Verify the token if it exists
  *     Removes the old token and sets up a new one if valid
  *
  * @param \Psecio\Gatekeeper\AuthTokenModel $token Token model instance
  * @return boolean Pass/fail result of the validation
  */
 public function verify(\Psecio\Gatekeeper\AuthTokenModel $token = null)
 {
     if (!isset($this->data[$this->tokenName])) {
         return false;
     }
     if ($token === null) {
         $tokenParts = explode(':', $this->data[$this->tokenName]);
         $token = $this->getById($tokenParts[0]);
     }
     if ($token === false) {
         return false;
     }
     $user = $token->user;
     $userToken = $token->token;
     // Remove the token (a new one will be made later)
     $this->datasource->delete($token);
     if (\Psecio\Gatekeeper\Gatekeeper::hash_equals($this->data[$this->tokenName], $token->id . ':' . hash('sha256', $userToken)) === false) {
         return false;
     }
     $this->setup($user);
     return $user;
 }