Удобный и Быстрый Хостинг для сайтов на WordPress. Пользуюсь сам и вам рекомендую!

wp_hash_password()WP 2.5.0

Шифрует переданный текст. Шифр всегда получается уникальный. Используется для шифрования паролей.

Создает хэш из простого текста. Хэш всегда получается разный, т.е. если 2 раза одинаково вызвать функцию, результаты будут отличаться. см. пример 1.

Функция использует класс PasswordHash, который расположен в /wp-includes/class-phpass.php. PasswordHash можно конфигурировать, смотрите пример.

Pluggable функция — эту функцию можно заменить из плагина. Это значит, что она будет работать (подключается) только после подключения всех плагинов, а до этого момента функция еще не определена... Поэтому нельзя вызывать эту и зависящие от неё функции прямо из кода плагина. Их нужно вызывать через хук plugins_loaded или позднее, например хук init.

Замена функции (переопределение) — в must-use или обычном плагине можно создать функцию с таким же названием, тогда она заменит текущую функцию.

Основа для: wp_set_password()
1 раз — 0.003847 сек (очень медленно) | 50000 раз — 106.27 сек (тормоз) | PHP 7.2.5, WP 4.9.8

Возвращает

Строку. Строку, зашифрованный пароль.

Использование

$hash = wp_hash_password( $password );
$password(строка) (обязательный)
Обычный текст (пароль), который нужно зашифровать.

Примеры

1

#1 Сравним уже зашифрованный пароль с обычным

$wp_hasher = new PasswordHash( 8, TRUE );

$password_hashed = '$P$B55D6LjfHDkINU5wF.v2BuuzO0/XPk/';
$plain_password  = 'test';

if( $wp_hasher->CheckPassword($plain_password, $password_hashed) ) {
	echo "Пароли совпадают";
}
else {
	echo "Пароль не верный";
}
0

#2 Пример работы функции

echo wp_hash_password( 'my_pass' ); //> $P$B1tp3GD53ykbIGC4hf84pvbEjSUloq.

// зашифруем еще раз точно также
echo wp_hash_password( 'my_pass' ); //> $P$Bu3CWn/Y0zTG8IXJ8ee9yiT715tWxG/
0

#3 Установим глобальную переменную $wp_hasher

Чтобы пароль создавался с нужными нам параметрами:

global $wp_hasher;
$wp_hasher = new PasswordHash(16, FALSE);
$hashedPassword = wp_hash_password($password);

Заметки

  • Global. PasswordHash. $wp_hasher phpass object.

Список изменений

С версии 2.5.0 Введена.
С версии 6.8.0 The password is now hashed using bcrypt by default instead of phpass.

Код wp_hash_password() WP 7.0

function wp_hash_password(
	#[\SensitiveParameter]
	$password
) {
	global $wp_hasher;

	if ( ! empty( $wp_hasher ) ) {
		return $wp_hasher->HashPassword( trim( $password ) );
	}

	if ( strlen( $password ) > 4096 ) {
		return '*';
	}

	/**
	 * Filters the hashing algorithm to use in the password_hash() and password_needs_rehash() functions.
	 *
	 * The default is the value of the `PASSWORD_BCRYPT` constant which means bcrypt is used.
	 *
	 * **Important:** The only password hashing algorithm that is guaranteed to be available across PHP
	 * installations is bcrypt. If you use any other algorithm you must make sure that it is available on
	 * the server. The `password_algos()` function can be used to check which hashing algorithms are available.
	 *
	 * The hashing options can be controlled via the {@see 'wp_hash_password_options'} filter.
	 *
	 * Other available constants include:
	 *
	 * - `PASSWORD_ARGON2I`
	 * - `PASSWORD_ARGON2ID`
	 * - `PASSWORD_DEFAULT`
	 *
	 * @since 6.8.0
	 * @since 7.0.0 The `$algorithm` parameter is now always a string.
	 *
	 * @param string $algorithm The hashing algorithm. Default is the value of the `PASSWORD_BCRYPT` constant.
	 */
	$algorithm = apply_filters( 'wp_hash_password_algorithm', PASSWORD_BCRYPT );

	/**
	 * Filters the options passed to the password_hash() and password_needs_rehash() functions.
	 *
	 * The default hashing algorithm is bcrypt, but this can be changed via the {@see 'wp_hash_password_algorithm'}
	 * filter. You must ensure that the options are appropriate for the algorithm in use.
	 *
	 * @since 6.8.0
	 * @since 7.0.0 The `$algorithm` parameter is now always a string.
	 *
	 * @param array  $options   Array of options to pass to the password hashing functions.
	 *                          By default this is an empty array which means the default
	 *                          options will be used.
	 * @param string $algorithm The hashing algorithm in use.
	 */
	$options = apply_filters( 'wp_hash_password_options', array(), $algorithm );

	// Algorithms other than bcrypt don't need to use pre-hashing.
	if ( PASSWORD_BCRYPT !== $algorithm ) {
		return password_hash( $password, $algorithm, $options );
	}

	// Use SHA-384 to retain entropy from a password that's longer than 72 bytes, and a `wp-sha384` key for domain separation.
	$password_to_hash = base64_encode( hash_hmac( 'sha384', trim( $password ), 'wp-sha384', true ) );

	// Add a prefix to facilitate distinguishing vanilla bcrypt hashes.
	return '$wp' . password_hash( $password_to_hash, $algorithm, $options );
}
2 комментария