PHP 8.3.27 Released!

password_hash

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

password_hashСоздаёт хеш пароля

Описание

password_hash(#[\SensitiveParameter] string $password, string|int|null $algo, array $options = []): string

Функция password_hash() создаёт хеш пароля через сильный необратимый алгоритм хеширования.

Поддерживаются следующие алгоритмы:

  • PASSWORD_DEFAULT — алгоритм хеширования bcrypt. С PHP 5.5.0 bcrypt стал алгоритмом по умолчанию. По мере добавления в PHP новых усиленных алгоритмов значение константы изменяется и задаёт новый идентификатор алгоритма. При изменении алгоритма длина результата изменяется, часто увеличивается. Поэтому сохранять результат в базе данных лучше в столбце длиной больше 60 байтов. Длину поля устанавливают равной 255 байтам, чтобы сократить риск ошибок.
  • PASSWORD_BCRYPT — алгоритм хеширования bcrypt. С этой константой функция генерирует стандартный хеш с идентификатором $2y$, совместимый с хешем, который создаёт функция crypt().
  • PASSWORD_ARGON2I — алгоритм хеширования Argon2i. Алгоритм доступен, только если PHP скомпилировали с поддержкой Argon2.
  • PASSWORD_ARGON2ID — алгоритм хеширования Argon2id. Алгоритм доступен, только если PHP скомпилировали с поддержкой Argon2.

Алгоритм PASSWORD_BCRYPT поддерживает следующие опции:

  • salt (string) — пользовательская соль для хеширования пароля. Ручная установка соли переопределит поведение функции — предотвратит автоматическую генерацию соли.

    При пропуске параметра функция password_hash() сгенерирует случайную соль для каждого хешируемого пароля. Это предпочтительный режим работы.

    Внимание

    Опция salt устарела в пользу соли по умолчанию, которую функция генерирует автоматически. Начиная с PHP 8.0.0 функция игнорирует пользовательскую соль.

  • cost (int) — алгоритмическая сложность. Пример работы с опцией приводит страница функции crypt().

    При пропуске параметра функция выберет значение по умолчанию: 12. Со значением по умолчанию функция генерирует стойкий хеш, но конкретное значение подстраивают под конкретное оборудование.

Алгоритмы PASSWORD_ARGON2I и PASSWORD_ARGON2ID поддерживают следующие опции:

  • memory_cost (int) — максимальный размер памяти в килобайтах для вычисления хеша Argon2. По умолчанию функция выбирает значение константы PASSWORD_ARGON2_DEFAULT_MEMORY_COST.

  • time_cost (int) — предельное количество раундов, которые выполняет алгоритм Argon2 для вычисления хеша. Значение по умолчанию: PASSWORD_ARGON2_DEFAULT_TIME_COST.

  • threads (int) — количество потоков для вычисления хеша алгоритмом Argon2. Значение по умолчанию: PASSWORD_ARGON2_DEFAULT_THREADS.

    Внимание

    Опция доступна, только если PHP собрали с библиотекой libargon2, а не с libsodium.

Список параметров

password

Пользовательский пароль.

Предостережение

При хешировании пароля алгоритмом PASSWORD_BCRYPT значение аргумента password усекается до предельной длины — 72 байтов.

algo

Константа алгоритма хеширования пароля, который будет использовать функция.

options

Ассоциативный массив с опциями. За документацией по поддерживаемым опциям для каждого алгоритма обратитесь к разделу Константы алгоритмов хеширования паролей.

Возвращаемые значения

Функция возвращает хешированный пароль.

Идентификатор алгоритма, показатель вычислительной сложности и соль возвращаются в составе хеша, поэтому не требуется хранить информацию об алгоритме и соли отдельно, а для проверки пароля достаточно передать хеш в функцию password_verify().

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

Версия Описание
8.4.0 Значение по умолчанию для опции cost алгоритма PASSWORD_BCRYPT увеличили с 10 до 12.
8.3.0 Функция password_hash() теперь устанавливает базовое исключение Random\RandomException в качестве значения свойства Exception::$previous, если выбрасывается ошибка ValueError из-за сбоя во время генерации соли.
8.0.0 Функция password_hash() больше не возвращает значение false, если возникла ошибка. Вместо этого функция выбросит ошибку ValueError, если алгоритм хеширования пароля недействителен, или ошибку Error, если не получилось захешировать пароль из-за неизвестной ошибки.
8.0.0 Параметр algo теперь принимает значение null.
7.4.0 Параметр algo теперь ожидает строку (string), но всё ещё принимает целое число (int) для обратной совместимости.
7.4.0 Модуль sodium обеспечивает альтернативную реализацию паролей Argon2.
7.3.0 Ввели константу PASSWORD_ARGON2ID, которая добавила поддержку алгоритма хеширования паролей алгоритмом Argon2id.
7.2.0 Ввели константу PASSWORD_ARGON2I, которая добавила поддержку хеширования паролей алгоритмом Argon2i.

Примеры

Пример #1 Пример хеширования пароля функцией password_hash()

<?php

echo password_hash("rasmuslerdorf", PASSWORD_DEFAULT);

?>

Вывод приведённого примера будет похож на:

$2y$12$4Umg0rCJwMswRw/l.SwHvuQV01coP0eWmGzd61QH2RvAOMANUBGC.

Пример #2 Пример генерации хеша функцией password_hash() установкой алгоритмической сложности вручную

<?php

$options
= [
// Увеличиваем алгоритмическую сложность алгоритма bcrypt с 12 до 13
'cost' => 13,
];

echo
password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options);

?>

Вывод приведённого примера будет похож на:

$2y$13$xeDfQumlmdm0Sco.4qmH1OGfUUmOcuRmfae0dPJhjX1Bq0yYhqbNi

Пример #3 Пример поиска оптимума показателя алгоритмической сложности для функции password_hash()

Код протестирует машину и определит показатель вычислительной сложности, с которым функция сгенерирует стойкий хеш, но не испортит пользовательский опыт и не замедлит другие операции, которые выполняет машина. Тестирование начинают с базового значения 11 и увеличивают показатель, если машина не замедляет работу под нагрузкой. Код ищет максимум, при котором хеширование не превышает 350 миллисекунд — допустимая задержка для систем авторизации пользователей.

<?php

$timeTarget
= 0.350; // 350 миллисекунд

$cost = 11;

do {
$cost++;
$start = microtime(true);
password_hash("test", PASSWORD_BCRYPT, ["cost" => $cost]);
$end = microtime(true);
} while ((
$end - $start) < $timeTarget);

echo
"Оптимальная стоимость: " . $cost - 1;

?>

Вывод приведённого примера будет похож на:

Оптимальная стоимость: 13

Пример #4 Пример генерации хеша функцией password_hash() алгоритмом Argon2i

<?php

echo 'Хеш Argon2i: ' . password_hash('rasmuslerdorf', PASSWORD_ARGON2I);

?>

Вывод приведённого примера будет похож на:

Хеш Argon2i: $argon2i$v=19$m=1024,t=2,p=2$YzJBSzV4TUhkMzc3d3laeg$zqU/1IN0/AogfP4cmSJI1vc8lpXRW9/S0sYY2i2jHT0

Примечания

Предостережение

Функция автоматически создаст безопасную соль, поэтому разработчики PHP настоятельно рекомендуют не указывать опцию salt вручную.

В PHP 7.0.0 установка значения опции salt вручную сгенерирует предупреждение об устаревании. В PHP 8.0.0 установку пользовательской соли удалили.

Замечание:

Работу функции тестируют на конкретной машине и подстраивают параметры вычислительной сложности до значений, с которыми при авторизации пользователей функция выполняется не дольше 350 миллисекунд. Скрипт в предыдущем примере помогает определить оптимум алгоритмической сложности для алгоритма bcrypt.

Замечание: Обновление алгоритмов, которые поддерживает функция, или изменение алгоритма по умолчанию подчиняется следующим правилам:

  • С момента включения нового алгоритма в ядро до установки по умолчанию прошёл 1 полный выпуск PHP. Алгоритм, который ввели в версии 7.5.5, получит право стать алгоритмом по умолчанию только в версии 7.7, поскольку версия 7.6 станет первым полным выпуском. Но и другой алгоритм, который добавили бы в версии 7.6.0, тоже получил бы право стать алгоритмом по умолчанию в версии 7.7.0.
  • Алгоритм по умолчанию изменяется только в полном выпуске, например, 7.3.0 или 8.0.0, но не в промежуточных. Единственное исключение — критическая уязвимость безопасности, которую обнаружили в текущем алгоритме по умолчанию.

Смотрите также

  • password_verify() - Проверяет, соответствует ли пароль хешу
  • password_needs_rehash() - Проверяет, что указанный хеш соответствует заданным опциям
  • crypt() - Хеширует строку необратимым способом
  • sodium_crypto_pwhash_str() - Получает ASCII-кодированный хеш

Добавить

Примечания пользователей 8 notes

up
159
phpnetcomment201908 at lucb1e dot com
6 years ago
Since 2017, NIST recommends using a secret input when hashing memorized secrets such as passwords. By mixing in a secret input (commonly called a "pepper"), one prevents an attacker from brute-forcing the password hashes altogether, even if they have the hash and salt. For example, an SQL injection typically affects only the database, not files on disk, so a pepper stored in a config file would still be out of reach for the attacker. A pepper must be randomly generated once and can be the same for all users. Many password leaks could have been made completely useless if site owners had done this.Since there is no pepper parameter for password_hash (even though Argon2 has a "secret" parameter, PHP does not allow to set it), the correct way to mix in a pepper is to use hash_hmac(). The "add note" rules of php.net say I can't link external sites, so I can't back any of this up with a link to NIST, Wikipedia, posts from the security stackexchange site that explain the reasoning, or anything... You'll have to verify this manually. The code:// config.confpepper=c1isvFdxMDdmjOlvxpecFw<?php// register.php$pepper = getConfigVariable("pepper");$pwd = $_POST['password'];$pwd_peppered = hash_hmac("sha256", $pwd, $pepper);$pwd_hashed = password_hash($pwd_peppered, PASSWORD_ARGON2ID);add_user_to_database($username, $pwd_hashed);?><?php// login.php$pepper = getConfigVariable("pepper");$pwd = $_POST['password'];$pwd_peppered = hash_hmac("sha256", $pwd, $pepper);$pwd_hashed = get_pwd_from_db($username);if (password_verify($pwd_peppered, $pwd_hashed)) {    echo "Password matches.";}else {    echo "Password incorrect.";}?>Note that this code contains a timing attack that leaks whether the username exists. But my note was over the length limit so I had to cut this paragraph out.Also note that the pepper is useless if leaked or if it can be cracked. Consider how it might be exposed, for example different methods of passing it to a docker container. Against cracking, use a long randomly generated value (like in the example above), and change the pepper when you do a new install with a clean user database. Changing the pepper for an existing database is the same as changing other hashing parameters: you can either wrap the old value in a new one and layer the hashing (more complex), you compute the new password hash whenever someone logs in (leaving old users at risk, so this might be okay depending on what the reason is that you're upgrading).Why does this work? Because an attacker does the following after stealing the database:password_verify("a", $stolen_hash)password_verify("b", $stolen_hash)...password_verify("z", $stolen_hash)password_verify("aa", $stolen_hash)etc.(More realistically, they use a cracking dictionary, but in principle, the way to crack a password hash is by guessing. That's why we use special algorithms: they are slower, so each verify() operation will be slower, so they can try much fewer passwords per hour of cracking.)Now what if you used that pepper? Now they need to do this:password_verify(hmac_sha256("a", $secret), $stolen_hash)Without that $secret (the pepper), they can't do this computation. They would have to do:password_verify(hmac_sha256("a", "a"), $stolen_hash)password_verify(hmac_sha256("a", "b"), $stolen_hash)...etc., until they found the correct pepper.If your pepper contains 128 bits of entropy, and so long as hmac-sha256 remains secure (even MD5 is technically secure for use in hmac: only its collision resistance is broken, but of course nobody would use MD5 because more and more flaws are found), this would take more energy than the sun outputs. In other words, it's currently impossible to crack a pepper that strong, even given a known password and salt.
up
45
nicoSWD
12 years ago
I agree with martinstoeckli,don't create your own salts unless you really know what you're doing.By default, it'll use /dev/urandom to create the salt, which is based on noise from device drivers.And on Windows, it uses CryptGenRandom().Both have been around for many years, and are considered secure for cryptography (the former probably more than the latter, though).Don't try to outsmart these defaults by creating something less secure. Anything that is based on rand(), mt_rand(), uniqid(), or variations of these is *not* good.
up
6
fullstadev at gmail dot com
1 year ago
Similar to another post made here about the use of strings holding null-bytes within password_hash(), I wanted to be a little more precise, as we've had quite some issues now. I've had a project of an application generating random hashes (CSPRN). What they've done is that they've used random_bytes(32), and the applied password_hash() to that obtained string, with the bcrypt algorithm. This on one side led to the fact that sometimes, random_bytes() generated a string with null-bytes, actually resulting to an error in their call to password_hash() (PHP v 8.2.18). Thanks to that ("Bcrypt password must not contain a null character") I modified the the function generating random hashes to encoding the obtained binary random string with random_bytes() using bin2hex() (or base64 or whatever), to assure that the string to be hashed has no null-bytes. I then just wanted to add that, when you use the bcrypt algorithm, make sure to remember that bcrypt truncates your password at 72 characters. When encoding your random string (e.g. generated using random_bytes()), this will convert your string from binary to hex representation, e.g. doubling its length. What you generally want is that your entire password is still contained within the 72 characters limit, to be sure that your entire "random information" gets hashes, and not only part of it.
up
6
bhare at duck dot com
2 years ago
If you are you going to use bcrypt then you should pepper the passwords with random large string, as commodity hardware can break bcrypt 8 character passwords within an hour; https://www.tomshardware.com/news/eight-rtx-4090s-can-break-passwords-in-under-an-hour
up
32
Lyo Mi
9 years ago
Please note that password_hash will ***truncate*** the password at the first NULL-byte.http://blog.ircmaxell.com/2015/03/security-issue-combining-bcrypt-with.htmlIf you use anything as an input that can generate NULL bytes (sha1 with raw as true, or if NULL bytes can naturally end up in people's passwords), you may make your application much less secure than what you might be expecting.The password $a = "\01234567"; is zero bytes long (an empty password) for bcrypt.The workaround, of course, is to make sure you don't ever pass NULL-bytes to password_hash.
up
18
martinstoeckli
12 years ago
In most cases it is best to omit the salt parameter. Without this parameter, the function will generate a cryptographically safe salt, from the random source of the operating system.
up
6
ms1 at rdrecs dot com
6 years ago
Timing attacks simply put, are attacks that can calculate what characters of the password are due to speed of the execution.More at...https://paragonie.com/blog/2015/11/preventing-timing-attacks-on-string-comparison-with-double-hmac-strategyI have added code to phpnetcomment201908 at lucb1e dot com's suggestion to make this possible "timing attack" more difficult using the code phpnetcomment201908 at lucb1e dot com posted.$pph_strt = microtime(true);//.../*The code he posted for login.php*///...$end = (microtime(true) - $pph_strt);$wait = bcmul((1 - $end), 1000000);  // usleep(250000) 1/4 of a secondusleep ( $wait );echo "<br>Execution time:".(microtime(true) - $pph_strt)."; ";Note I suggest changing the wait time to suit your needs but make sure that it is more than than the highest execution time the script takes on your server.Also, this is my workaround to obfuscate the execution time to nullify timing attacks. You can find an in-depth discussion and more from people far more equipped than I for cryptography at the link I posted. I do not believe this was there but there are others. It is where I found out what timing attacks were as I am new to this but would like solid security.
up
11
Mike Robinson
11 years ago
For passwords, you generally want the hash calculation time to be between 250 and 500 ms (maybe more for administrator accounts). Since calculation time is dependent on the capabilities of the server, using the same cost parameter on two different servers may result in vastly different execution times. Here's a quick little function that will help you determine what cost parameter you should be using for your server to make sure you are within this range (note, I am providing a salt to eliminate any latency caused by creating a pseudorandom salt, but this should not be done when hashing passwords):<?php/** * @Param int $min_ms Minimum amount of time in milliseconds that it should take * to calculate the hashes */function getOptimalBcryptCostParameter($min_ms = 250) {    for ($i = 4; $i < 31; $i++) {        $options = [ 'cost' => $i, 'salt' => 'usesomesillystringforsalt' ];        $time_start = microtime(true);        password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options);        $time_end = microtime(true);        if (($time_end - $time_start) * 1000 > $min_ms) {            return $i;        }    }}echo getOptimalBcryptCostParameter(); // prints 12 in my case?>
To Top