百科狗-知识改变命运!
--

password_hash() - php 密码散列哈希函数

是丫丫呀1年前 (2023-11-21)阅读数 16#技术干货
文章标签算法

password_hash()

(PHP 5 >= 5.5.0, PHP 7)

创建密码的散列(hash)

说明

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

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
  • PASSWORD_ARGON2I-使用 Argon2 散列算法创建散列。

PASSWORD_BCRYPT支持的选项:

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

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

    Warning

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

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

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

PASSWORD_ARGON2I支持的选项:

  • password_hash() - php 密码散列哈希函数

    memory_cost(integer)-计算 Argon2 散列时的最大内存(单位:字节 byte)。默认值:PASSWORD_ARGON2_DEFAULT_MEMORY_COST

  • time_cost(integer)-计算 Argon2 散列时最多的时间。默认值:PASSWORD_ARGON2_DEFAULT_TIME_COST

  • threads(integer)-计算 Argon2 散列时最多的线程数。默认值:PASSWORD_ARGON2_DEFAULT_THREADS

参数

$password

用户的密码。

Caution

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

$algo

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

$options

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

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

返回值

返回散列后的密码,或者在失败时返回FALSE

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

范例

Example #1password_hash()例子

以上例程的输出类似于:

$2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a

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

以上例程的输出类似于:

$2y$12$QjSH496pcT5CEbzjD/vtVeH03tfHKFy36d4J0Ltp3lRtee9HDxY3K

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

以上例程的输出类似于:

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

寻找最佳 cost 的password_hash()例子

以上例程的输出类似于:

Appropriate Cost Found: 10

使用 Argon2 的password_hash()例子

以上例程的输出类似于:

Argon2 hash: $argon2i$v=19$m=1024,t=2,p=2$YzJBSzV4TUhkMzc3d3laeg$zqU/1IN0/AogfP4cmSJI1vc8lpXRW9/S0sYY2i2jHT0

注释

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,等等),不能是在修订版。唯一的例外是:在当前默认算法里发现了紧急的安全威胁。

更新日志

版本说明
7.2.0添加PASSWORD_ARGON2I,支持 Argon2 密码散列算法。

参见

  • password_verify() 验证密码是否和散列值匹配
  • crypt() 单向字符串散列
  • »用户的使用
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
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


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.
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.
You can produce the same hash in php 5.3.7+ with crypt() function: 
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.
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
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.
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): 
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 "
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.
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.
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.
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.
I believe a note should be added about the compatibility of crypt() and password_hash().
My tests showed that yes, password_verify can also take hashes generated by crypt - as well as those from password_hash. But vice versa this is not true...
You cannot put hashes generated by password_hash into crypt for comparing them themselves, when used as the salt for crypt, as was recommended years ago (compare user entry with user crypt(userentry,userentry). No big deal, but it means that password checking routines MUST immediately be rewritten to use password_hash...
You cannot start using password_hash for hash generation without also altering the password check routine!
So the word "compatible" should be, IMHO, ammended with a word of caution, hinting the reader, that compatibility here is a one-way street.

鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com

免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)

图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)