hash_equals

函式
hash_equals ( $known_string, $user_string )
引數
  • (string) $known_string Expected string.
    Required:
  • (string) $user_string Actual, user supplied, string.
    Required:
返回值
  • (bool) Whether strings are equal.
定義位置
相關方法
has_metahas_blockshas_taghas_termis_email
引入
3.9.2
棄用
-

hash_equals – 這是一個PHP函式,以抵抗定時攻擊的方式對兩個字串進行比較。計時攻擊是一種安全漏洞,在比較敏感資訊,如密碼或認證令牌時可能發生。hash_equals函式需要兩個引數:第一個要比較的字串和第二個要比較的字串。如果字串相等,它返回真,如果不相等,則返回假。

計時攻擊安全的字串比較。

使用相同的時間比較兩個字串,無論它們是否相等。

注意:當提供不同長度的引數時,它可能洩露字串的長度。

該函式在 PHP 5.6 中被新增。然而,Hash 擴充套件可能在選定的伺服器上被明確禁用。從 PHP 7.4.0 開始,Hash 擴充套件是一個核心的 PHP 擴充套件,不能再禁用。
不能再被禁用。也就是說,當 PHP 7.4.0 成為最低要求時,這個 polyfill 可以被安全地移除。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
function hash_equals( $known_string, $user_string ) {
$known_string_length = strlen( $known_string );
if ( strlen( $user_string ) !== $known_string_length ) {
return false;
}
$result = 0;
// Do not attempt to "optimize" this.
for ( $i = 0; $i < $known_string_length; $i++ ) {
$result |= ord( $known_string[ $i ] ) ^ ord( $user_string[ $i ] );
}
return 0 === $result;
}
endif;
// random_int() was introduced in PHP 7.0.
if ( ! function_exists( 'random_int' ) ) {
require ABSPATH . WPINC . '/random_compat/random.php';
}
function hash_equals( $known_string, $user_string ) { $known_string_length = strlen( $known_string ); if ( strlen( $user_string ) !== $known_string_length ) { return false; } $result = 0; // Do not attempt to "optimize" this. for ( $i = 0; $i < $known_string_length; $i++ ) { $result |= ord( $known_string[ $i ] ) ^ ord( $user_string[ $i ] ); } return 0 === $result; } endif; // random_int() was introduced in PHP 7.0. if ( ! function_exists( 'random_int' ) ) { require ABSPATH . WPINC . '/random_compat/random.php'; }
function hash_equals( $known_string, $user_string ) {
		$known_string_length = strlen( $known_string );

		if ( strlen( $user_string ) !== $known_string_length ) {
			return false;
		}

		$result = 0;

		// Do not attempt to "optimize" this.
		for ( $i = 0; $i < $known_string_length; $i++ ) {
			$result |= ord( $known_string[ $i ] ) ^ ord( $user_string[ $i ] );
		}

		return 0 === $result;
	}
endif;

// random_int() was introduced in PHP 7.0.
if ( ! function_exists( 'random_int' ) ) {
	require ABSPATH . WPINC . '/random_compat/random.php';
}

常見問題

FAQs
檢視更多 >