You are here

public static function Crypt::hashEquals in Service Container 7.2

Same name and namespace in other branches
  1. 7 lib/Drupal/Component/Utility/Crypt.php \Drupal\Component\Utility\Crypt::hashEquals()

Compares strings in constant time.

Parameters

string $known_string: The expected string.

string $user_string: The user supplied string to check.

Return value

bool Returns TRUE when the two strings are equal, FALSE otherwise.

File

lib/Drupal/Component/Utility/Crypt.php, line 146
Contains \Drupal\Component\Utility\Crypt.

Class

Crypt
Utility class for cryptographically-secure string handling routines.

Namespace

Drupal\Component\Utility

Code

public static function hashEquals($known_string, $user_string) {
  if (function_exists('hash_equals')) {
    return hash_equals($known_string, $user_string);
  }
  else {

    // Backport of hash_equals() function from PHP 5.6
    // @see https://github.com/php/php-src/blob/PHP-5.6/ext/hash/hash.c#L739
    if (!is_string($known_string)) {
      trigger_error(sprintf("Expected known_string to be a string, %s given", gettype($known_string)), E_USER_WARNING);
      return FALSE;
    }
    if (!is_string($user_string)) {
      trigger_error(sprintf("Expected user_string to be a string, %s given", gettype($user_string)), E_USER_WARNING);
      return FALSE;
    }
    $known_len = strlen($known_string);
    if ($known_len !== strlen($user_string)) {
      return FALSE;
    }

    // This is security sensitive code. Do not optimize this for speed.
    $result = 0;
    for ($i = 0; $i < $known_len; $i++) {
      $result |= ord($known_string[$i]) ^ ord($user_string[$i]);
    }
    return $result === 0;
  }
}