且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

你能帮我理解盐哈希函数吗?

更新时间:2023-11-03 18:55:28

PHP的crypt函数将所有属性打包为60个字符的字符串(用于BCrypt)。

  $ 2y $ 10 $ nOUIs5kJ7naTuTFkBy1veuK0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa 
| | | |
| | |散列值= K0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa
| | |
| | salt = nOUIs5kJ7naTuTFkBy1veu(22个字符)
| |
|成本因子= 10 = 2 ^ 10迭代
|
hash-algorithm = 2y = BCrypt

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



PHP函数 password_hash() password_verify()只是crypt函数的包装器,并且会处理关键部分,比如生成一个安全salt。


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 )

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).

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'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.

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.