欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

password_hash

(PHP 5 >= 5.5.0, PHP 7)

password_hash — 创建密码的哈希(hash)

说明

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

password_hash() 使用足够强度的单向散列算法创建密码的哈希(hash)。 password_hash() 兼容 crypt()。 所以,crypt() 创建的密码哈希也可用于 password_hash()

当前支持的算法:

 

  • PASSWORD_DEFAULT - 使用 bcrypt 算法 (PHP 5.5.0 默认)。 注意,该常量会随着 PHP 加入更新更高强度的算法而改变。 所以,使用此常量生成结果的长度将在未来有变化。 因此,数据库里储存结果的列可超过60个字符(最好是255个字符)。
  • PASSWORD_BCRYPT - 使用 CRYPT_BLOWFISH 算法创建哈希。 这会产生兼容使用 "$2y$" 的 crypt()。 结果将会是 60 个字符的字符串, 或者在失败时返回 FALSE

    支持的选项:

    • salt - 手动提供哈希密码的盐值(salt)。这将避免自动生成盐值(salt)。

      省略此值后,password_hash() 会为每个密码哈希自动生成随机的盐值。这种操作是有意的模式。

      Warning

      盐值(salt)选项从 PHP 7.0.0 开始被废弃(deprecated)了。 现在最好选择简单的使用默认产生的盐值。

    • cost - 代表算法使用的 cost。crypt() 页面上有 cost 值的例子。

      省略时,默认值是 10。 这个 cost 是个不错的底线,但也许可以根据自己硬件的情况,加大这个值。

参数

password

用户的密码。

Caution

使用PASSWORD_BCRYPT 做算法,将使 password 参数最长为72个字符,超过会被截断。

algo

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

options

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

省略后,将使用随机盐值与默认 cost。

返回值

返回哈希后的密码, 或者在失败时返回 FALSE

使用的算法、cost 和盐值作为哈希的一部分返回。所以验证哈希值的所有信息都已经包含在内。 这使password_verify() 函数验证的时候,不需要额外储存盐值或者算法的信息。

范例

 

Example #1 password_hash() 例子

<?php
/**
 * 我们想要使用默认算法哈希密码
 * 当前是 BCRYPT,并会产生 60 个字符的结果。
 *
 * 请注意,随时间推移,默认算法可能会有变化,
 * 所以需要储存的空间能够超过 60 字(255字不错)
 */

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

以上例程的输出类似于:

$2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a

 

Example #2 password_hash() 手动设置 cost 的例子

<?php
/**
 * 在这个案例里,我们为 BCRYPT 增加 cost 到 12。
 * 注意,我们已经切换到了,将始终产生 60 个字符。
 */

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

以上例程的输出类似于:

$2y$12$QjSH496pcT5CEbzjD/vtVeH03tfHKFy36d4J0Ltp3lRtee9HDxY3K

 

Example #3 password_hash() 手动设置盐值的例子

<?php
/**
 * 注意,这里的盐值是随机产生的。
 * 永远都不要使用固定盐值,或者不是随机生成的盐值。
 *
 * 绝大多数情况下,可以让 password_hash generate 为你自动产生随机盐值
 */

$options = [
    
'cost' => 11,
    
'salt' => mcrypt_create_iv(22MCRYPT_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
/**
 * 这个例子对服务器做了基准测试(benchmark),检测服务器能承受多高的 cost
 * 在不明显拖慢服务器的情况下可以设置最高的值
 * 8-10 是个不错的底线,在服务器够快的情况下,越高越好。
 * 以下代码目标为  ≤ 50 毫秒(milliseconds),
 * 适合系统处理交互登录。
 */

$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

强烈建议不要自己为这个函数生成盐值(salt)。只要不设置,它会自动创建安全的盐值。

就像以上提及的,在 PHP 7.0 提供 salt选项会导致废弃(deprecation)警告。 未来的 PHP 发行版里,手动提供盐值的功能可能会被删掉。

Note:

在交互的系统上,推荐在自己的服务器上测试此函数,调整 cost 参数直至函数时间开销小于 100 毫秒(milliseconds)。 上面脚本的例子会帮助选择合适硬件的最佳 cost。

Note这个函数更新支持的算法时(或修改默认算法),必定会遵守以下规则:

 

  • 任何内核中的新算法必须在经历一次 PHP 完整发行才能成为默认算法。 比如,在 PHP 7.5.5 中添加的新算法,在 PHP 7.7 之前不能成为默认算法 (由于 7.6 是第一个完整发行版)。 但如果是在 7.6.0 里添加的不同算法,在 7.7.0 里也可以成为默认算法。
  • 仅仅允许在完整发行版中修改默认算法(比如 7.3.0, 8.0.0,等等),不能是在修订版。 唯一的例外是:在当前默认算法里发现了紧急的安全威胁。

参见

 

add a note add a note

User Contributed Notes 13 notes

martinstoeckli ¶
3 years ago
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
nicoSWD ¶
2 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.
anonymous ¶
8 months ago
Pay close attention to the maximum allowed length of the password parameter!  If you exceed the maximum length, it will be truncated without warning.

If you prepend your own salt/pepper to the password, and that salt/pepper exceeds the maximum length, then this function will truncate the actual password.  That means password_verify() will return true with ANY password using the same salt/pepper.

It might be a good idea to append any salt/pepper to the end of the password instead.
Cloxy ¶
2 years ago
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;

?>
darkflib ¶
2 months ago
Timings:

Note: 1 and 2 for cost are invalid.

3  -  0.085115432739258ms
4  -  1.6319751739502ms
5  -  2.9170513153076ms
6  -  5.511999130249ms
7  -  10.689973831177ms
8  -  20.890951156616ms
9  -  41.686058044434ms
10  -  84.12504196167ms (default)
11  -  168.97416114807ms
12  -  334.79714393616ms
13  -  680.88603019714ms
14  -  1342.1139717102ms
15  -  2706.4559459686ms
16  -  5404.2019844055ms
17  -  10615.604162216ms

For an average site the default of 10 is probably a sane enough value.
lortet ¶
11 months ago
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>
Lyo Mi ¶
8 months 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.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.
Mike Robinson ¶
2 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
?>
VladimirMozhenkov at yahoo dot com ¶
1 year ago
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.
martinstoeckli ¶
3 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.
cottton ¶
2 years ago
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.
chris at acsdi dot com ¶
3 years ago
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.
jessieschraaff at hotmail dot com ¶
11 months ago
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);
 
来自  http://php.net/manual/zh/function.password-hash.php
普通分类: