diff --git a/src/wp-includes/pluggable.php b/src/wp-includes/pluggable.php index 3dd629fa1990c..d0b2d3602a980 100644 --- a/src/wp-includes/pluggable.php +++ b/src/wp-includes/pluggable.php @@ -2581,18 +2581,38 @@ function wp_salt( $scheme = 'auth' ) { if ( ! function_exists( 'wp_hash' ) ) : /** - * Gets hash of given string. + * Gets the hash of the given string. + * + * 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. * * @since 2.0.3 + * @since 6.8.0 The `$algo` parameter was added. + * + * @throws InvalidArgumentException if the hashing algorithm is not supported. * * @param string $data Plain text to hash. * @param string $scheme Authentication scheme (auth, secure_auth, logged_in, nonce). + * @param string $algo Hashing algorithm to use. Default: 'md5'. * @return string Hash of $data. */ - function wp_hash( $data, $scheme = 'auth' ) { + function wp_hash( $data, $scheme = 'auth', $algo = 'md5' ) { $salt = wp_salt( $scheme ); - return hash_hmac( 'md5', $data, $salt ); + // 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 ); } endif; diff --git a/tests/phpunit/tests/functions/wpHash.php b/tests/phpunit/tests/functions/wpHash.php new file mode 100644 index 0000000000000..63744b188dace --- /dev/null +++ b/tests/phpunit/tests/functions/wpHash.php @@ -0,0 +1,39 @@ +assertSame( $expected_length, strlen( $hash ) ); + } + + public function data_wp_hash_uses_specified_algorithm() { + return array( + array( 'md5', 32 ), + array( 'sha1', 40 ), + array( 'sha256', 64 ), + ); + } + + /** + * @ticket 62005 + */ + public function test_wp_hash_throws_exception_on_invalid_algorithm() { + $this->expectException( 'InvalidArgumentException' ); + + wp_hash( 'data', 'auth', 'invalid' ); + } +} diff --git a/tests/phpunit/tests/pluggable/signatures.php b/tests/phpunit/tests/pluggable/signatures.php index 81fd079621916..8ac1dfb6966b6 100644 --- a/tests/phpunit/tests/pluggable/signatures.php +++ b/tests/phpunit/tests/pluggable/signatures.php @@ -209,6 +209,7 @@ public function get_pluggable_function_signatures() { 'wp_hash' => array( 'data', 'scheme' => 'auth', + 'algo' => 'md5', ), 'wp_hash_password' => array( 'password' ), 'wp_check_password' => array(