【问题标题】:hashing password with salt用盐散列密码
【发布时间】:2014-03-04 15:24:03
【问题描述】:

我通过互联网搜索并找到了哈希密码的功能。但是
我无法处理存储在数据库中的散列密码。我正在使用的函数生成随机密码,因为它与随机生成的盐连接。 当用户想要更改他的密码时,问题就出现了。

current_password = random hashed password( which must match the one stored in db).

if(current_password == $db_password){

    enter new password

}

上述条件不成立,因为密码总是随机的。

我的功能

function cryptPass($input,$rounds = 9) {
    $salt = "";
    $saltChars = array_merge(range('A','Z'),range('a','z'),range(0,9));
    for($i = 0;$i < 22; $i++){
        $salt .= $saltChars[array_rand($saltChars)];
    }
    return crypt($input,sprintf('$2y$%02d$', $rounds).$salt);
}
$pass = "password";
$hashedPass = cryptPass($pass);

echo $hashedPass;

i have 3 column in my user table (id, username, password).

谁能告诉我如何正确使用这个功能, 或者有没有最好的方法来做到这一点?

【问题讨论】:

  • 将盐与密码一起存储在表中。

标签: php hash


【解决方案1】:

您希望将生成的$salt 与散列密码一起存储在数据库中。然后,当您检查密码时,您将能够从数据库中获取盐并再次在散列过程中使用它。

所以您的数据库表中有一个名为“salt”的额外列

(id, username, password, salt)

【讨论】:

  • 这不是问题,因为 crypt() 函数在生成的哈希值中包含盐,并且为了验证它会自动从存储的哈希值中提取盐。
【解决方案2】:

您需要执行与登录相同的步骤。检查输入的旧密码是否与数据库中的密码哈希匹配,然后根据输入的新密码创建一个哈希并存储它。

PHP 已经有一个函数 password_hash() 来创建一个哈希值,以及一个函数 password_verify() 来检查输入的密码是否与存储的密码哈希值匹配。

// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT);

// 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);

所以你的代码看起来像这样:

if (password_verify(current_password, $db_password))
{
  enter new password
}

【讨论】:

  • password_hash() 在 php 5.5 之前的 php 版本中可用吗?
  • @dxcoder1 - 是的,早期的 PHP 版本有一个 compatibility pack。因此,您可以使用相同的“面向未来”的功能(稍后您可以删除兼容包)。即使对于 5.3.7 之前的 PHP,也有可能,看看这个answer
最近更新 更多