文字

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.

      Warning

      The salt option has been deprecated as of PHP 7.0.0. It is now preferred to simply use the salt that is generated by default.

    • 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

用户的密码。

Caution

Using the PASSWORD_BCRYPT as the algorithm, will result in the password parameter being truncated to a maximum length of 72 characters.

algo

一个用来在散列密码时指示算法的密码算法常量。

options

一个包含有选项的关联数组。目前支持两个选项:salt,在散列密码时加的盐(干扰字符串),以及cost,用来指明算法递归的层数。这两个值的例子可在 crypt() 页面找到。

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.

范例

Example #1 password_hash() example

<?php

echo  password_hash ( "rasmuslerdorf" PASSWORD_DEFAULT ). "\n" ;
?>

以上例程的输出类似于:

$2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a

Example #2 password_hash() example setting cost manually

<?php

$options  = [
    
'cost'  =>  12 ,
];
echo 
password_hash ( "rasmuslerdorf" PASSWORD_BCRYPT $options ). "\n" ;
?>

以上例程的输出类似于:

$2y$12$QjSH496pcT5CEbzjD/vtVeH03tfHKFy36d4J0Ltp3lRtee9HDxY3K

Example #3 password_hash() example setting salt manually

<?php

$options  = [
    
'cost'  =>  11 ,
    
'salt'  =>  mcrypt_create_iv ( 22 MCRYPT_DEV_URANDOM ),
];
echo 
password_hash ( "rasmuslerdorf" PASSWORD_BCRYPT $options ). "\n" ;
?>

以上例程的输出类似于:

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

Example #4 password_hash() example finding a good cost

<?php

$timeTarget  0.05 // 50 milliseconds 

$cost  8 ;
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: 10

注释

Caution

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.

Note:

It is recommended that you test this function on your servers, and adjust the cost parameter so that execution of the function takes less than 100 milliseconds on interactive systems. The script in the above example will help you choose a good cost value for your hardware.

Note: Updates to supported algorithms by this function (or changes to the default one) must follow the following 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.

参见

  • password_verify() - Verifies that a password matches a hash
  • crypt() - 单向字符串散列
  • » userland implementation

用户评论:

[#1] jessieschraaff at hotmail dot com [2015-10-02 08:54:09]

For me it didn't work, so I asked my friend and he told me to remove ."/n"

So it worked like this
$password = password_hash($password, PASSWORD_DEFAULT);

[#2] lortet [2015-09-18 08:52:00]

The PASSWORD_BCRYPT duration evolves exponentially based on COST.

Measure picture : https://static.lortet.io/files/php.net.bcrypt_evolves.png
The "constant" depends on your machine (for me is 1).

Method :
<table border="1">
<?php
    
for( $cost 0$cost <= 10$cost=$cost+0.1){
        
$start microtime(true);
        
password_hash("test".$costPASSWORD_BCRYPT, ["cost" => $cost]);
        
$end microtime(true);
        echo 
'<tr><td>' $cost '</td><td>' . ( $end $start ) . '</td></tr>';
    }
?>

</table>

[#3] VladimirMozhenkov at yahoo dot com [2015-08-26 12:04:31]

Note that this function can return NULL. It does so if you provide an incorrect constant as an algorythm. I had the following:

$password = password_hash($password1, PASSWORD_BDCRYPT, array( 'cost' => 10 ));

and i couldn't understand why i kept having NULL written in $password; it was a simple fact that the constant was PASSWORD_BCRYPT.

[#4] Mike Robinson [2014-08-28 02:52:29]

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

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
?>

[#5] cottton [2014-02-17 16:29:54]

if you thought
"why is the salt included in the hash and is it save when i store it as it is in my db?"

Answer i found:
The salt just has to be unique. It not meant to be a secret.

As mentioned in notes and docu before: let password_hash() take care of the salt.

With the unique salt you force the attacker to crack the hash.
The hash is unique and cannot be found at rainbow tables.

[#6] Cloxy [2013-10-18 09:45:31]

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;

?>

[#7] nicoSWD [2013-10-06 03:29:34]

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.

[#8] chris at acsdi dot com [2013-06-21 16:29:03]

Alan is entirely wrong, please ignore his comment and/or vote it down. This method encodes the algorithm and other parameters into the returned hash.

Deliberately specifying the algorithm to use should only be done in a carefully considered scenario, and these functions are designed and policies have been decided to ensure wide compatibility.

The risk of forcing a particular algorithm is that your code will continue to use a weaker algorithm as newer ones are implemented and strengthened.

[#9] martinstoeckli [2013-03-08 22:36:28]

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.

[#10] martinstoeckli [2012-12-17 20:56:40]

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

上一篇: 下一篇: