password_hash

(PHP 5 >= 5.5.0)

password_hashCreates a password hash

Описание

string password_hash ( string $password , integer $algo [, array $options ] )

password_hash() creates a new password hash using a strong one-way hashing algorithm. password_hash() is compatible with crypt(). Therefore, password hashes created by crypt() can be used with password_hash().

The following algorithms are currently supported:

  • PASSWORD_DEFAULT - Use the bcrypt algorithm (default as of PHP 5.5.0). Note that this constant is designed to change over time as new and stronger algorithms are added to PHP. For that reason, the length of the result from using this identifier can change over time. Therefore, it is recommended to store the result in a database column that can expand beyond 60 characters (255 characters would be a good choice).
  • PASSWORD_BCRYPT - Use the CRYPT_BLOWFISH algorithm to create the hash. This will produce a standard crypt() compatible hash using the "$2y$" identifier. The result will always be a 60 character string, или FALSE в случае возникновения ошибки.

    Supported Options:

    • salt - to manually provide a salt to use when hashing the password. Note that this will override and prevent a salt from being automatically generated.

      If omitted, a random salt will be generated by password_hash() for each password hashed. This is the intended mode of operation.

    • cost - which denotes the algorithmic cost that should be used. Examples of these values can be found on the crypt() page.

      If omitted, a default value of 10 will be used. This is a good baseline cost, but you may want to consider increasing it depending on your hardware.

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

password

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

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

Using the PASSWORD_BCRYPT for the algo parameter, will result in the password parameter being truncated to a maximum length of 72 characters. This is only a concern if are using the same salt to hash strings with this algorithm that are over 72 bytes in length, as this will result in those hashes being identical.

algo

Константа, обозначающая используемый алгоритм хэширования пароля.

options

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

If omitted, a random salt will be created and the default cost will be used.

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

Returns the hashed password, или FALSE в случае возникновения ошибки.

The used algorithm, cost and salt are returned as part of the hash. Therefore, all information that's needed to verify the hash is included in it. This allows the password_verify() function to verify the hash without needing separate storage for the salt or algorithm information.

Примеры

Пример #1 password_hash() example

<?php
/**
 * We just want to hash our password using the current DEFAULT algorithm.
 * This is presently BCRYPT, and will produce a 60 character result.
 *
 * Beware that DEFAULT may change over time, so you would want to prepare
 * By allowing your storage to expand past 60 characters (255 would be good)
 */
echo password_hash("rasmuslerdorf"PASSWORD_DEFAULT)."\n";
?>

Результатом выполнения данного примера будет что-то подобное:

$2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a

Пример #2 password_hash() example setting cost manually

<?php
/**
 * In this case, we want to increase the default cost for BCRYPT to 12.
 * Note that we also switched to BCRYPT, which will always be 60 characters.
 */
$options = [
    
'cost' => 12,
];
echo 
password_hash("rasmuslerdorf"PASSWORD_BCRYPT$options)."\n";
?>

Результатом выполнения данного примера будет что-то подобное:

$2y$12$QjSH496pcT5CEbzjD/vtVeH03tfHKFy36d4J0Ltp3lRtee9HDxY3K

Пример #3 password_hash() example setting salt manually

<?php
/**
 * Note that the salt here is randomly generated.
 * Never use a static salt or one that is not randomly generated.
 *
 * For the VAST majority of use-cases, let password_hash generate the salt randomly for you
 */
$options = [
    
'cost' => 11,
    
'salt' => mcrypt_create_iv(22MCRYPT_DEV_URANDOM),
];
echo 
password_hash("rasmuslerdorf"PASSWORD_BCRYPT$options)."\n";
?>

Результатом выполнения данного примера будет что-то подобное:

$2y$11$q5MkhSBtlsJcNEVsYh64a.aCluzHnGog7TQAKVmQwO9C8xb.t89F.

Пример #4 password_hash() example finding a good cost

<?php
/**
 * This code will benchmark your server to determine how high of a cost you can
 * afford. You want to set the highest cost that you can without slowing down
 * you server too much. 10 is a good baseline, and more is good if your servers
 * are fast enough.
 */
$timeTarget 0.2

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

echo 
"Appropriate Cost Found: " $cost "\n";
?>

Результатом выполнения данного примера будет что-то подобное:

Appropriate Cost Found: 11

Примечания

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

It is strongly recommended that you do not generate your own salt for this function. It will create a secure salt automatically for you if you do not specify one.

Замечание:

It is recommended that you should test this function on your servers, and adjust the cost parameter so that execution of the function takes approximately 0.1 to 0.5 seconds. The script in the above example will help you choose a good cost value for your hardware.

Замечание: Updates to supported algorithms by this function (or changes to the default one) must follow the follwoing rules:

  • Any new algorithm must be in core for at least 1 full release of PHP prior to becoming default. So if, for example, a new algorithm is added in 5.5.5, it would not be eligible for default until 5.7 (since 5.6 would be the first full release). But if a different algorithm was added in 5.6.0, it would also be eligible for default at 5.7.0.
  • The default should only change on a full release (5.6.0, 6.0.0, etc) and not on a revision release. The only exception to this is in an emergency when a critical security flaw is found in the current default.

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

Коментарии

Автор:
There is a compatibility pack available for PHP versions 5.3.7 and later, so you don't have to wait on version 5.5 for using this function. It comes in form of a single php file:
https://github.com/ircmaxell/password_compat
2012-12-17 22:56:40
http://php5.kiev.ua/manual/ru/function.password-hash.html
Автор:
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.
2013-03-09 00:36:28
http://php5.kiev.ua/manual/ru/function.password-hash.html
Автор:
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.
2013-10-06 06:29:34
http://php5.kiev.ua/manual/ru/function.password-hash.html
Автор:
You can produce the same hash in php 5.3.7+ with crypt() function:

<?php

$salt 
mcrypt_create_iv(22MCRYPT_DEV_URANDOM);
$salt base64_encode($salt);
$salt str_replace('+''.'$salt);
$hash crypt('rasmuslerdorf''$2y$10$'.$salt.'$');

echo 
$hash;

?>
2013-10-18 12:45:31
http://php5.kiev.ua/manual/ru/function.password-hash.html
Автор:
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
?>
2014-08-28 05:52:29
http://php5.kiev.ua/manual/ru/function.password-hash.html
Автор:
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.html

If 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.
2016-01-06 20:11:44
http://php5.kiev.ua/manual/ru/function.password-hash.html
Автор:
According to the draft specification, Argon2di is the recommended mode of operation:

> 9.4.  Recommendations
>
>   The Argon2id variant with t=1 and maximum available memory is
>   recommended as a default setting for all environments.  This setting
>   is secure against side-channel attacks and maximizes adversarial
>   costs on dedicated bruteforce hardware.

source: https://tools.ietf.org/html/draft-irtf-cfrg-argon2-06#section-9.4
2019-06-18 16:09:04
http://php5.kiev.ua/manual/ru/function.password-hash.html
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.conf
pepper=c1isvFdxMDdmjOlvxpecFw

<?php
// register.php
$pepper getConfigVariable("pepper");
$pwd $_POST['password'];
$pwd_peppered hash_hmac("sha256"$pwd$pepper);
$pwd_hashed password_hash($pwd_pepperedPASSWORD_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.
2019-08-25 17:17:05
http://php5.kiev.ua/manual/ru/function.password-hash.html
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-strategy

I 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 second

usleep ( $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.
2019-10-14 20:07:42
http://php5.kiev.ua/manual/ru/function.password-hash.html
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
2023-09-03 19:36:03
http://php5.kiev.ua/manual/ru/function.password-hash.html

    Поддержать сайт на родительском проекте КГБ