如何从bcrypt哈希密码中提取salt


How can I extract the salt out of bcrypt hash passwords?

我的数据库存储bcrypt密码,这意味着salt应该与一起存储在密码字段中。我不想在不需要的时候单独开垦一块地来储存盐。然而,当我想将用户发送给我的密码与数据库中存储的密码进行比较时,我需要对传入的密码进行相同的散列。问题:存储的哈希的哪一部分是盐?我想我可以使用简单的substr()返回salt。

// password stored in database.
$user->password_hash = password_hash($password, PASSWORD_BCRYPT, array('cost' => 13));

// password from form being compared to form password
$form_password_hash = password_hash($data['form-password'], PASSWORD_BCRYPT, array('cost' => 13));
if($user->getPasswordHash() == $form_password_hash)
{
    $user->setPassword($data['new-password']);
    return new Response("Your password has been changed");
}

Salt是散列中第三个$之后的前22个字符:

$2y$13$<this is the salt, 22 chars><this is the password hash>

但是,您不应该手动提取salt来验证密码——请使用password_verify函数。它将用户输入的密码作为第一个参数,将完整的哈希作为第二个参数,并正确处理salt。

您需要使用password_verify函数。此函数将解析散列后的密码字符串以查找salt并执行计算。

if (password_verify($data['form-password'], $user->getPasswordHash())) {
    echo 'Password is correct';
}