我是php的新手,我正在实现一个登录系统,用户可以在该系统中输入电子邮件和密码,并检查它们是否存在于数据库(phpmyadmin中的mysql)中
当用户首次注册时,使用此功能对密码进行加密:
/**
* Encrypting password
*
* @param
* password
* returns salt and encrypted password
*/
public function hashSSHA($password) {
$salt = sha1 ( rand () );
$salt = substr ( $salt, 0, 10 );
$encrypted = base64_encode ( sha1 ( $password . $salt, true ) . $salt );
$hash = array (
"salt" => $salt,
"encrypted" => $encrypted
);
return $hash;
}
salt参数是解密密码的密钥,它与用户信息一起存储在数据库中,解密代码为:
/**
* Decrypting password
*
* @param
* salt, password
* returns hash string
*/
public function checkhashSSHA($salt, $password) {
$hash = base64_encode ( sha1 ( $password . $salt, true ) . $salt );
return $hash;
}
当我用输入的电子邮件和密码去获取用户时,密码就会被解密。
/**
* Get user by email and password
*/
public function getUserByEmailAndPassword($email, $password) {
$stmt = $this->conn->prepare ( "SELECT * FROM users WHERE email = ?" );
$stmt->bind_param ( "s", $email );
if ($stmt->execute ()) {
$user = $stmt->get_result ()->fetch_assoc ();
$stmt->close ();
$salt = $user ["salt"];
$hash = $this->checkhashSSHA ( $salt, $user ["encrypted_password"] );
if ($hash == $password) {
return $user;
} else {
return NULL;
}
} else {
return NULL;
}
}
问题是,当用户输入正确的电子邮件和密码时,该代码仍然返回NULL,我怀疑处理密码部分有问题。
Siguza的回答是正确的,但您对他的回答的评论反映了一种非常合理的混淆,因为checkhashSSHA()
函数的名称有点误导(即其名称与其行为不匹配)。以"check"开头的函数名应该返回布尔值。我建议将其更改为:
/**
* Decrypting password
*
* @param
* password, hash, salt
* returns boolean
*/
public function checkhashSSHA($password, $hash, $salt) {
$hash2 = base64_encode ( sha1 ( $password . $salt, true ) . $salt );
return ($hash == $hash2) ;
}
现在更改这两行:
$hash = $this->checkhashSSHA ( $salt, $user ["encrypted_password"] );
if ($hash == $password) {
到这一行:
if (checkhashSSHA($password, $user["encrypted_password"], $salt)) {
现在,它更清晰、更易于使用,而且它的行为与其名称相匹配。然而,如果你想增强代码中的命名,这里有一些建议:
- 将
checkhashSSHA()
更改为compareHashSSHA()
- 将数据库中的
encrypted_password
更改为hashed_password
更重要的是,sha1哈希算法有点旧,而且不太安全。我建议将其更改为更安全的哈希,如sha512。查看此并阅读Kai Petzke的评论,了解完整的故事。
问题在于这两行:
$hash = $this->checkhashSSHA ( $salt, $user ["encrypted_password"] );
if ($hash == $password) {
首先,您正在散列已经散列过的密码,而不是明文密码
然后你将"哈希中的哈希"与明文密码进行比较
所以你在做hash(hash(pw)) == pw
,而它应该是hash(pw) == hash(pw)
。
您只需交换$user ["encrypted_password"]
和$password
:
$hash = $this->checkhashSSHA ( $salt, $password );
if ($hash == $user ["encrypted_password"]) {
我建议您不要使用sshhash函数,而是查看php函数password_verify()
请在此处查看有关该功能和相关功能的文档:http://php.net/manual/en/function.password-verify.php