php - 如何将密码解密为要在更新表单 Yii2(高级模板)中显示的真实密码?

标签 php yii2 yii2-advanced-app

我想在更新表单中显示解密密码作为行

<?= $form->field($model, 'password_hash')->passwordInput() ?>

显示完整长度的加密密码,如:

$2y$13$4SUKFKV03ZolfDwLIsZRBuD4i7iELPZRMEJojODgP3s5S4dER.J0m

希望它是 123456 的加密密码

最佳答案

正如@TomCarrick 已经提到的,散列密码是一种单向算法,永远不会被逆转。验证建议密码有效性的过程是使用相同的算法对其进行哈希处理,然后检查生成的哈希值是否与您已有的哈希值相同。这个策略在 Yii 中处理 User class , 扩展 IdentityInterface 的那个并在您的配置文件中定义。这是在这两种方法中完成的:

class User extends ActiveRecord implements IdentityInterface
{
    ...

    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

NOTE: The following is not recommended. If it is for update form like user changing his password as I understood from your question then I would recommend using two inputs: old_password and new_password as used in most websites. Then the same way as implemented in the User class, you may check the intered password validity by comparing hashes and if it is valid then you just hash the new_password and save it to database by overriding the old one.

如果出于某种原因,您需要知道用户的密码,那么您将需要通过实现LESS SECURE 策略来手动更改 Yii 设置和验证这些密码的方式,这可以是通过用一种不同的算法替换这种单向算法来实现,比如使用 encryptByPassword()decryptByPassword()辅助方法,它允许您使用 $secretKey 加密任何字符串,稍后您将使用它来解密它。所以你需要通过这个覆盖前面提到的 2 个方法:

public $secretKey = 'WHATEVER_SECRET_YOU_CHOOSE';

public function validatePassword($password)
{
    $decryptedPassword = Yii::$app->getSecurity()->decryptByPassword($this->password_hash, $this->secretKey);
    return $decryptedPassword === $password;
}

public function setPassword($password)
{
    $this->password_hash = Yii::$app->getSecurity()->encryptByPassword($password, $this->secretKey);
}

如果需要,您还可以在您的模型中实现 setter 和 getter 方法,例如:

public function getPassword()
{
    return Yii::$app->getSecurity()->decryptByPassword($this->password_hash, 'THE_SECRET_YOU_ALREADY_HAVE_CHOOSEN');
}

public function setPassword($password)
{
    $this->password_hash = Yii::$app->getSecurity()->encryptByPassword($password, 'THE_SECRET_YOU_ALREADY_HAVE_CHOOSEN');
}

您可以在任何地方使用来检索真实密码,并且至少在数据库中保留它的解密版本:

<?= $form->field($model, 'password')->passwordInput() ?>

您还可以找到更多关于安全辅助方法的信息 here .

关于php - 如何将密码解密为要在更新表单 Yii2(高级模板)中显示的真实密码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35660817/

相关文章:

javascript - 从 google reCaptcha v2 中删除手动挑战

php - 排序规则 utf8mb4_unicode_ci 是什么意思

Yii2:从 '$this->goBack()' 排除特定的 Controller Action

php - 在 yii2 中获取未知属性异常

Yii2 翻译动态内容的最佳实践

arrays - 如何在 yii2 中使用 findAll() ?

php - 在 yii2 中迁移时出现异常 'could not find driver'

php - 如何使单个值更新 SQL 查询与 Wordpress 中的 $wpdb 类一起使用?

php - 使用 GD 获取图像所有像素图的更好方法

Yii2 下拉列表中的多个选定值