hashEquals() public static method

Very short timing attack safe string comparison for PHP < 5.6 http://php.net/manual/en/function.hash-equals.php#118384.
public static hashEquals ( string $a, string $b ) : boolean
$a string
$b string
return boolean
Example #1
0
 /**
  * Decrypt the given value.
  *
  * @param string $value
  * 
  * @return string
  */
 private function decrypt($value)
 {
     $this->checkKey();
     $decoded = base64_decode($value);
     $hmac = mb_substr($decoded, 0, 32, '8bit');
     $iv = mb_substr($decoded, 32, 16, '8bit');
     $cipher = mb_substr($decoded, 48, null, '8bit');
     $calculated = hash_hmac('sha256', $iv . $cipher, $this->authentication, true);
     if (Helpers::hashEquals($hmac, $calculated)) {
         $value = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $this->key, $cipher, 'ctr', $iv), "");
         return json_decode($value, true);
     }
 }
Example #2
0
 /**
  * Decrypt the given value.
  *
  * @param string $value
  * 
  * @return string
  */
 private function decrypt($value)
 {
     if (empty($this->key) || empty($this->authentication)) {
         throw new RuntimeException('No crypt keys provided');
     }
     $decoded = base64_decode($value);
     $hmac = mb_substr($decoded, 0, 32, '8bit');
     $iv = mb_substr($decoded, 32, 16, '8bit');
     $cipher = mb_substr($decoded, 48, null, '8bit');
     $calculated = hash_hmac('sha256', $iv . $cipher, $this->authentication, true);
     if (Helpers::hashEquals($hmac, $calculated)) {
         $value = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $this->key, $cipher, 'ctr', $iv), "");
         return json_decode($value, true);
     }
 }
Example #3
0
 /**
  * Validate the request.
  *
  * @param ServerRequestInterface $request
  * @param array                  &$tokens
  *
  * @return bool
  */
 private function validateRequest(ServerRequestInterface $request, array &$tokens)
 {
     $data = $request->getParsedBody();
     if (!isset($data[$this->formIndex]) || !isset($data[$this->formToken])) {
         return false;
     }
     $index = $data[$this->formIndex];
     $token = $data[$this->formToken];
     if (!isset($tokens[$index])) {
         return false;
     }
     $stored = $tokens[$index];
     unset($tokens[$index]);
     $lockTo = $request->getUri()->getPath();
     if (!Utils\Helpers::hashEquals($lockTo, $stored['lockTo'])) {
         return false;
     }
     $expected = self::encode(hash_hmac('sha256', ClientIp::getIp($request), base64_decode($stored['token']), true));
     return Utils\Helpers::hashEquals($token, $expected);
 }