public static function Crypt::hashEquals

public static Crypt::hashEquals($known_string, $user_string)

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

core/lib/Drupal/Component/Utility/Crypt.php, line 87

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;
  }
}

© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.
https://api.drupal.org/api/drupal/core!lib!Drupal!Component!Utility!Crypt.php/function/Crypt::hashEquals/8.1.x