As already mentioned by @TomCarrick, hashing passwords is a one way algorithm and never meant to be reversed. The process of verifying the validity of a proposed password is by hashing it using the same algorithm then checking if the resulting hash is same as the one you already have. This strategy is handled in Yii within the User class, the one extending the IdentityInterface and defined in your config file. And this is done within those 2 methods :
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.
If for whatever reasons you have, you need to know user's passwords then you will need to manually change the way how Yii is setting and validating those passwords by implementing a LESS SECURE strategy and this can be achieved by replacing that one way algorithm by a different one like using encryptByPassword() and decryptByPassword() helper methods which will allow you to encrypt any string using a $secretKey
that you will use later to decrypt it back. So you will need to override the previously mentioned 2 methods by this :
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);
}
If needed you can also implement setter and getter methods inside your model like :
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');
}
that you can use any where to retrieve the real password and at least keeping a decrypted version of it in database :
<?= $form->field($model, 'password')->passwordInput() ?>
You may also find more about security helper methods here.