From 0fc42c64439666e23d1046e54f4caf5815712fd0 Mon Sep 17 00:00:00 2001
From: John Blackbourn <johnbillion@git.wordpress.org>
Date: Mon, 6 Jan 2025 15:23:26 +0000
Subject: [PATCH] Security: Enhance the `wp_hash()` function to support custom
 hashing algorithms.

The default algorithm remains as md5, but this change allows any algorithm that's supported by `hash_hmac()` to be used instead.

Props pushpenderindia, ayeshrajans, debarghyabanerjee, johnbillion

Fixes #62005

Built from https://develop.svn.wordpress.org/trunk@59578


git-svn-id: http://core.svn.wordpress.org/trunk@58964 1a063a9b-81f0-0310-95a4-ce76da25c4cd
---
 wp-includes/pluggable.php | 26 +++++++++++++++++++++++---
 wp-includes/version.php   |  2 +-
 2 files changed, 24 insertions(+), 4 deletions(-)

diff --git a/wp-includes/pluggable.php b/wp-includes/pluggable.php
index 3dd629fa19..d0b2d3602a 100644
--- a/wp-includes/pluggable.php
+++ b/wp-includes/pluggable.php
@@ -2581,18 +2581,38 @@ endif;
 
 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/wp-includes/version.php b/wp-includes/version.php
index 4d0ca9c050..6c09a703c9 100644
--- a/wp-includes/version.php
+++ b/wp-includes/version.php
@@ -16,7 +16,7 @@
  *
  * @global string $wp_version
  */
-$wp_version = '6.8-alpha-59577';
+$wp_version = '6.8-alpha-59578';
 
 /**
  * Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema.