lithium\util\String::compare PHP Метод

compare() публичный статический Метод

To successfully mitigate timing attacks and not leak the actual length of the known string, it is important that _both provided strings have the same length_ and that the _user-supplied string is passed as a second parameter_ rather than first. This function has the same signature and behavior as the native hash_equals() function and will use that function if available (PHP >= 5.6). An E_USER_WARNING will be emitted when either of the supplied parameters is not a string.
public static compare ( string $known, string $user ) : boolean
$known string The string of known length to compare against.
$user string The user-supplied string.
Результат boolean Returns a boolean indicating whether the two strings are equal.
    public static function compare($known, $user)
    {
        if (function_exists('hash_equals')) {
            return hash_equals($known, $user);
        }
        if (!is_string($known) || !is_string($user)) {
            trigger_error('Expected `$known` & `$user` parameters to be strings.', E_USER_WARNING);
            return false;
        }
        if (($length = strlen($known)) !== strlen($user)) {
            return false;
        }
        for ($i = 0, $result = 0; $i < $length; $i++) {
            $result |= ord($known[$i]) ^ ord($user[$i]);
        }
        return $result === 0;
    }

Usage Example

Пример #1
0
 /**
  * Compares a password and its hashed value using PHP's `crypt()`. Rather than a simple string
  * comparison, this method uses a constant-time algorithm to defend against timing attacks.
  *
  * @see lithium\security\Password::hash()
  * @see lithium\security\Password::salt()
  * @param string $password The user-supplied plaintext password to check.
  * @param string $hash The known hashed password to compare it to.
  * @return boolean Returns a boolean indicating whether the password is correct.
  */
 public static function check($password, $hash)
 {
     return String::compare($hash, crypt($password, $hash));
 }
All Usage Examples Of lithium\util\String::compare