Best location to md5 the password

Hi all,

I have confuse where should I md5 the password. If I put it on the beforeSave() on the User model, I will have a problem when updating the module, the already md5 password will be md5 again. At the moment, I put a check on the beforeSave() so that the password with length = 32 will not be md5 again. The only drawback with this solution is that the user cannot have a password with exactly 32 characters.

Any suggestion?

Thank you,


You can check the value of $yourmodel->isNewRecord.


And try to don’t use md5 in the future, it is not very safe. Instead, choose sha256/sha512 (or other) with random salt. Just for your security ;)


I do not use $yourmodel->isNewRecord since it is ok in registration (create) but will not handle change/update password of existing user.


Thanks for the advice. I will try to look at the sha1. Which one is better, double hashing or random salt? However, random salt key should be stored somewhere since I need to match the password when the user is login.

You can add property newPassword to your model. The corresponding field should appear in an update form. In your rules() you should define it “safe” for “update” scenario (‘on’=>‘update’). In the beforeSave() method just check it for emptyness (if not empty, then $this->password = md5($this->newPassword)).

Double hashing or simple salt don’t give a very big additional security. If users type the same passwords, they will still hash to the same value (not good at all). And yes, you will need one more field in the database to store randomly generated salt (CHAR(16) should be enough).

sha1 has proven collision attacks and isn’t recommended. Use sha256, sha512, whirlpool…


This is one of the most frequently asked questions :)

Please check e.g. this:


Thanks for pointing it out. Somehow, I am overwhelmed with the categories of the forum. Hence, I only used General Discussion for Yii 1.1.x category for all of my post.

Apologise to this mistake. I will more carefully (search forum for the existence before posting a new one).

To all of you, thank you for the quick and helpful responses.

$password = crypt(md5($password),md5($salt));

no need for a 32 character field in your database … just VARCHAR(13) ;)

Just do it inside the register action (user controller).

$model->password=hash('sha256', $salt.$model->attributes['password']);