我使用了带有blowfish算法的crypt函数(单向散列)并且我在db中保存了我的散列字符串没有问题。
$hash=$2y$13$1wVxPniVSiKTjBmDxUhykeec08.v0UsujEkmhjHECIUgEiSuJFag
$actual=crypt("kumar",$hash);
这些用于验证密码的方法是获取我们当前的密码和我们可以存储到数据库中的哈希密码。
在这些过程中,他们将与以下代码进行比较
public function compareString($expected, $actual)
{
$expected .= "\0";
$actual .= "\0";
$expectedLength = StringHelper::byteLength($expected);
$actualLength = StringHelper::byteLength($actual);
$diff = $expectedLength - $actualLength;
for ($i = 0; $i < $actualLength; $i++) {
$diff |= (ord($actual[$i]) ^ ord($expected[$i % $expectedLength]));
}
return $diff === 0;
}
当密码正确或不正确时,它仅返回0或1.
但我的问题是这些如何将当前密码与我们在db中保存的哈希密码相匹配。因为当前密码只包含字符串而哈希密码包含cost,salt,哈希密码。
他们是仅验证密码还是只验证盐或它们是如何进行验证的?
我想要验证内置密码算法密码的验证。
答案 0 :(得分:1)
对于初学者,我建议使用函数password_hash()和password_verify()来检查密码,在内部使用crypt()函数。
// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($password, PASSWORD_DEFAULT);
// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($password, $existingHashFromDb);
但您似乎对crypt()如何使用其哈希验证密码感兴趣。创建第一个哈希时,将crypt-parameters作为第二个参数传递,它包含算法,成本因子和salt(格式在此answer中解释)。
为了验证您可以再次计算哈希值,但是您需要完全相同的crypt参数,然后您将获得类似的哈希值。第一个散列使用crypt-parameters启动,当您将第二个参数作为第二个参数传递时,crypt()函数从第一个散列中提取这些参数。
$2y$13$1wVxPniVSiKTjBmDxUhyke
在您的示例中,这部分哈希包含crypt-parameters,它是哈希的开头,crypt()再次使用它来验证密码。