lithium\util\String::compare()

public static method

Compares two strings in constant time to prevent timing attacks.

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.

Parameters

  • string $known

    The string of known length to compare against.

  • string $user

    The user-supplied string.

Returns

boolean

Returns a boolean indicating whether the two strings are equal.

Source

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