2014-03-04 206 views
2

我已经通过网络搜索过,发现哈希密码的函数。但
我有麻烦处理存储在数据库中的散列密码。我正在使用的函数会生成随机密码,因为它与随机生成的盐级联在一起。 用户想要更改密码时出现问题。哈希密码加盐

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

任何一个可以告诉我如何正确使用此功能, 还是有做这一个最好的方法?

+1

商店与密码一起在食盐。 –

回答

0

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

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

所以您的代码会是这个样子:

​​
+0

是在php 5.5之前的php版本中可用的password_hash()吗? – dxcoder1

+0

@ dxcoder1 - 对于早期的PHP版本,有[兼容包](https://github.com/ircmaxell/password_compat/blob/master/lib/password.php)。因此,您可以使用相同的“未来证明”功能(稍后您可以删除兼容包)。即使对于5.3.7之前的PHP有一个可能性,看看这个[答](http://stackoverflow.com/a/22260436/575765)。 – martinstoeckli

0

您想要存储数据库中生成的$salt以及散列密码。然后,当你来检查密码时,你将能够从数据库中获取盐并再次用于哈希过程。

因此,与您的数据库表有它的一个额外的列被称为“盐”

(id, username, password, salt) 
+0

谢谢,这应该做到这一点。 – dxcoder1

+0

这不是问题,因为crypt()函数在生成的哈希值中包含salt,并且为了验证,它会自动从存储的哈希值中提取salt。 – martinstoeckli