yii中的解密和加密密码

时间:2016-08-02 16:41:14

标签: database encryption passwords yii2

这是我的代码:

//save user in DB
$email='user1@email.com';
$username='user1';
$password='user1';
echo 'No hashed password='.$password.'<br>';
$user= new User();
$user->email=$email;
$user->username=$username;
$user->password=Yii::$app->getSecurity()->generatePasswordHash($password);
echo 'Hashed password='.$user->password;
echo '<br>';
$user->save();

//check user
$password2 ='user1';
$password2=Yii::$app->getSecurity()->generatePasswordHash($password2); //do hash
echo 'Hashed password2='.$password2;
$check_user=User::find()->where(['email' => $email])->one();
if($check_user) { //if user found
    if (Yii::$app->getSecurity()->validatePassword($password2, $check_user->password)) {
        echo  'Yes';
    } else {
        echo 'No';
    }
}

我将数据(电子邮件,用户名,密码)保存在数据库中。当我想查看我的密码时,我总是得到。 我怎样才能解决我的问题?

1 个答案:

答案 0 :(得分:1)

检查密码时,您不需要生成新哈希。只需将信息($password2)与您保存的哈希值($check_user->password)进行比较。

//check user
$password2 ='user1';
echo 'password2 = ' . $password2 . '<br />';

$check_user=User::find()->where(['email' => $email])->one();

if($check_user) //if user found
{
    if (Yii::$app->getSecurity()->validatePassword($password2, $check_user->password)) {
        echo  'Yes';
    } else {
        echo 'No';
    }
}

您可以在文档中找到更多信息:herehere