Best place to hash the password

I am very new to Yii, so bare with me as I get my feet wet.

I want passwords to be stored with MD5 (or whatever works). Where would be the best place to do this?

User controller? User model? Higher up?

Could you give an example?


User Model in beforeSave method.

here is a sample code

  public function beforeSave() {

        if (parent::beforeSave() && $this->isNewRecord) {

            // for example

            $this->password = md5($this->password . Yii::app()->params['saltString']);


        return true;


I would just suggest using or something similar as using MD5 for passwords is a bad idea.


The fact that rainbow tables exist for MD5 hashes does not mean it is a poor method. What it means is that you should salt your hashes so that brute force attacks using tables become infeasible.

Using sha1() with unique salt should be sufficient for most security needs.

I recently had the same question when starting out with Yii and opted go go with something like this:

class User extends CActiveRecord {

	// container for plaintext password when entered

	private $_password;


	 * Used to check if a given password matches the current password

	 * @return boolean True if the given password matches the users password


	public function validatePassword($password) {

		return $this->_hashPassword($password, $this->salt) == $this->password_hash;



	 * Changes the users password. Updates user salt as well.

	 * @param string $password


	public function setPassword($password) {

		$this->_password = $password;

		$this->salt = $this->_generateSalt();

		$this->password_hash = $this->_hashPassword($password, $this->salt);


	public function getPassword() {

		return $this->_password;



	 * Returns a hash based on the password and the salt

	 * @param string $password

	 * @param string $salt

	 * @return string sha1 hash


	private static function _hashPassword($password, $salt) {

		return sha1($salt.$password);



	 * @return string Random salt


	private static function _generateSalt() {

		return uniqid(null, true);



I was actually planning on using crypt().

$this->password = crypt($this->password,Yii::app()->params['saltString']);