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

How to decrypt password to real password to be shown in update form Yii2 (Advanced Template)?

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

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

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

ySUKFKV03ZolfDwLIsZRBuD4i7iELPZRMEJojODgP3s5S4dER.J0m

希望它是 123456

的加密密码

你不能。这就是散列密码的全部意义所在,因此它们无法还原为原始明文。

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

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() and 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