encryptByPassword() and save in mysql db

Hi guys,

I try to save a passwords with:

public function beforeSave($insert) {
        if (isset($this->db_password))
            
            $this->db_password = Yii::$app->getSecurity()->encryptByPassword($this->db_password, 'test');       

        return parent::beforeSave($insert);
    }

and get it back by

public function getPassword()
    {   
        return Yii::$app->security->decryptByKey($this->db_password, 'test');
    }

Unfortunately, I get nothing back. I try a mysql blob and string datatype (UTF8), I didn’t found something in the web.

Thanks for any help!

Best regards,
Toby

public function beforeSave($insert) {
        if ($insert && isset($this->db_password)) {
              //  Encrypt only before inserting
        }

cheers lanrenbulan,

I’had the problem to get back the pw in the right way (incorrectly: B@ "z¤Ô2f[ÆH]«žA89e336a8a48d995a566c5082140765f22dbe30ec90e43f319bc06bab0797d468ÞÅ^ø5·EìØ<¬­‡½–˺t•‰¨À‘ÏñyŒ,)

I’ve solved it by:

public function getPassword()
    {   
        
        return utf8_encode(\yii::$app->security->decryptByKey($this->db_password, 'test'));
    }

maybe it help someone

Never save user passwords like that. If any of users know you are doing this, they’ll quit your service and badmouth you. Moreover that gives hackers access to your text password if they manage to take the database and understand how you encrypt it.

always hash your passwords.

See this link for hashing:

For Yii check this guide to see how to do it correctly:

1 Like