函数文档

wp_hash()

💡 云策文档标注

概述

wp_hash() 是 WordPress 核心函数,用于获取给定字符串的哈希值,默认使用 md5 算法,但可通过参数指定其他 hash_hmac() 支持的算法。该函数依赖于 wp_salt() 获取盐值,并可被插件替换。

关键要点

  • 函数签名:wp_hash( $data, $scheme = 'auth', $algo = 'md5' ),返回哈希字符串
  • 参数说明:$data 为要哈希的纯文本(必需),$scheme 为认证方案(必需,如 auth、secure_auth、logged_in、nonce),$algo 为哈希算法(可选,默认 'md5')
  • 内部机制:使用 wp_salt() 获取盐值,并通过 hash_hmac() 生成哈希;如果算法不受支持,会抛出 InvalidArgumentException
  • 可扩展性:该函数可通过插件重新定义,若无插件定义则使用默认实现
  • 相关函数:与 wp_salt()、__() 等关联,被多个核心组件如 WP_REST_Widgets_Controller 和 wp_verify_nonce() 使用

代码示例

wp_hash( $data, $scheme );

注意事项

  • 在 WordPress 6.8.0 版本中增加了 $algo 参数,允许自定义哈希算法
  • 使用前应通过 hash_hmac_algos() 检查算法支持性,以避免运行时错误

📄 原文内容

Gets the hash of the given string.

Description

The default algorithm is md5 but can be changed to any algorithm supported by hash_hmac(). Use the hash_hmac_algos() function to check the supported algorithms.

Parameters

$datastringrequired
Plain text to hash.
$schemestringrequired
Authentication scheme (auth, secure_auth, logged_in, nonce).
$algostringrequired
Hashing algorithm to use. Default: 'md5'.

Return

string Hash of $data.

More Information

Usage:
wp_hash( $data, $scheme );
Notes:
  • This function can be replaced via plugins. If plugins do not redefine these functions, then this will be used instead.
  • Uses: wp_salt() Get WordPress salt.

Source

function wp_hash( $data, $scheme = 'auth', $algo = 'md5' ) {
	$salt = wp_salt( $scheme );

	// Ensure the algorithm is supported by the hash_hmac function.
	if ( ! in_array( $algo, hash_hmac_algos(), true ) ) {
		throw new InvalidArgumentException(
			sprintf(
				/* translators: 1: Name of a cryptographic hash algorithm. 2: List of supported algorithms. */
				__( 'Unsupported hashing algorithm: %1$s. Supported algorithms are: %2$s' ),
				$algo,
				implode( ', ', hash_hmac_algos() )
			)
		);
	}

	return hash_hmac( $algo, $data, $salt );
}

Changelog

Version Description
6.8.0 The $algo parameter was added.
2.0.3 Introduced.