Php 用盐散列密码

Php 用盐散列密码,php,hash,Php,Hash,我在网上搜索了一下,找到了散列密码的功能。但是 我无法处理数据库中存储的哈希密码。我正在使用的函数生成随机密码,因为它与随机生成的salt连接在一起。 当用户想要更改密码时,就会出现问题 current_password = random hashed password( which must match the one stored in db). if(current_password == $db_password){ enter new password } 由于密码始终

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

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).
函数cryptPass($input,$rounds=9){
$salt=“”;
$saltChars=array_merge(范围('A','Z')、范围('A','Z')、范围(0,9));
对于($i=0;$i<22;$i++){
$salt.=$saltChars[array_rand($saltChars)];
}
返回crypt($input,sprintf($2y$%02d$,$rounds)。$salt);
}
$pass=“password”;
$hashedPass=cryptPass($pass);
echo$hashedPass;
我的用户表中有3列(id、用户名、密码)。
有人能告诉我如何正确使用这个功能吗,
或者有没有最好的方法呢?

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

因此,您的数据库表中有一个额外的列,名为“salt”


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

PHP已经有了一个创建散列的函数,以及一个检查输入的密码是否与存储的密码散列匹配的函数

// 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
}

将盐与密码一起存储在表中。这不会是问题所在,因为crypt()函数将盐包含在生成的哈希值中,为了验证,它会自动从存储的哈希值中提取盐。是password_hash()吗在PHP5.5之前的php版本中提供?@dxcoder1-是的,在早期的php版本中有一个。因此,您可以使用相同的“未来证明”功能(稍后您可以删除兼容包)。即使对于5.3.7之前的PHP,也有可能出现这种情况,请看一看。
if (password_verify(current_password, $db_password))
{
  enter new password
}