你能帮我理解盐散列函数吗?

2022-01-22 00:00:00 hash passwords salt php

我正在学习各种密码散列技术,我发现一个教程让我对某些点有点怀疑.特别是,我只是希望您能重新确认/解释一些事情.例如,我发现了以下功能.现在,如果我很好地理解这是在做什么,它会生成一个盐,以防具有以下值:

I am going through various password hashing techniques and I found a tutorial which left me a bit dubious about some points. In particular, I just would like if you could reconfirm/explain a few things.For example i found the following function. Now if I understand well what this is doing, it's generating a salt which in case with the following values:

$salt = sprintf("$2a$%02d$", $cost) . $salt; // if $cost = 10 and $salt 234, then it should output $2a$1002d$234? 

其次,身份验证示例使用以下比较:

Secondly, the example for authentication uses the following comparison:

if ( crypt($password, $user->hash) === $user->hash )

它声明将密码与哈希值作为盐返回相同的哈希值" - 现在我检查了 php 文档,自然它声明相同,但我只是试图从理论上理解这个概念(我不喜欢重用东西,即使我知道如何使用,如果我不理解它背后的逻辑).

and it states that "Hashing the password with its hash as the salt returns the same hash" - now I checked the php documentation and naturally it states the same but I am just trying to understand the concept theoretically (I do not like to reuse stuff even if I know how to use if I don't understand the logic behind it).

我的问题是为什么 crypt($password, $hash) 返回相同的 $hash 值.我只是想了解它背后的逻辑.谢谢你.

My question is why crypt($password, $hash) is returning the same $hash value. I just want to understand the logics behind it. Thank you.

推荐答案

PHP 的 crypt 函数会将所有属性打包成一个 60 个字符的字符串(用于 BCrypt).

PHP's crypt function will pack all attributes into a 60 character string (for BCrypt).

$2y$10$nOUIs5kJ7naTuTFkBy1veuK0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa
 |  |  |                     |
 |  |  |                     hash-value = K0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa
 |  |  |
 |  |  salt = nOUIs5kJ7naTuTFkBy1veu (22 characters)
 |  |
 |  cost-factor = 10 = 2^10 iterations
 |
 hash-algorithm = 2y = BCrypt

现在,当您将存储的哈希作为第二个参数传递给函数进行验证时,将从该字符串中提取成本因子和盐,并重新用于计算新的哈希.这个哈希值是可比较的,因为使用了相同的参数.

Now when you pass the stored hash to the function as the second parameter for verification, the cost factor and the salt will be extracted from this string, and will be reused to calculate the new hash. This hash will be comparable, because the same parameters where used.

PHP 函数 password_hash() 和 password_verify() 只是 crypt 函数的包装器,将处理关键的部分,例如生成安全盐.

The PHP functions password_hash() and password_verify() are just wrappers around the crypt function, and will handle the crucial parts like generating a safe salt.

相关文章