Problem With Sha256 Login


I have created a login system where users are stored in a database. This was initially created without any password encryption method and worked fine. I have now tried to implement the SHA256 method but I am having problems logging in once a password has been encrypted.

The passwords are being encrypted when a new user is created and I can see the hashed password in the database. When I try to login however with the username and original password I get a ‘Incorrect Username or password’ error message.

My User model is:

      public function beforeSave() {

            $user = Yii::app()->user;

            if ($this->isNewRecord) {

                  $this->user_created = new CDbExpression('NOW()');

                  $this->user_created_by = $user !== null ? intval($user->id) : 0;

                  $this->user_login_password = hash_hmac('sha256', $this->user_login_password, Yii::app()->params['encryptionKey']);


            $this->user_updated = new CDbExpression('NOW()');

            $this->user_updated_by = $user !== null ? intval($user->id) : 0;

            return parent::beforeSave();


My login authentication code is:

 class UserIdentity extends CUserIdentity {

      private $_id;

      public function authenticate() {

            $record = Users :: model()->findByAttributes(array('user_login_id' => $this->username));

            if ($record === null)

                  $this->errorCode = self :: ERROR_USERNAME_INVALID;


            //if ($record->user_login_password !== $this->password)

            if ($record->user_login_password !== hash_hmac('sha256', $this->password, Yii::app()->params['encryptionKey']))

                  $this->errorCode = self :: ERROR_PASSWORD_INVALID;

            else {

                  $this->_id = $record->user_id;

                  $this->setState('user_account_status', $record->user_account_status);

                  $this->setState('user_screen_name', $record->user_screen_name);

                  $this->errorCode = self :: ERROR_NONE;


            return !$this->errorCode;


      public function getId() {

            return $this->_id;



My login form is:

<div class="account-container login">

      <div class="clearfix">


            $form = $this->beginWidget('CActiveForm', array(

                'id' => 'login-form',

                'enableClientValidation' => true,

                'clientOptions' => array(

                    'validateOnSubmit' => true,




            <div style="padding: 14px 0 2px 17px;">

                  <div style="float:right;margin:2px 14px 0 0;"><?php echo CHtml::image(Yii::app()->theme->baseUrl . "/images/logo_login.png", "Admin"); ?></div>

                  <h1> Auction Database</h1>

                  <div class="login-fields">

                        <p>Please login using your registered account details:</p>

                        <div class="field"> <?php echo $form->labelEx($model, 'Username'); ?> <?php echo $form->textField($model, 'username', array('class' => 'login username-field', 'placeholder' => 'Username')); ?> <?php echo $form->error($model, 'username'); ?> </div>

                        <div class="field"> <?php echo $form->labelEx($model, 'Password'); ?> <?php echo $form->passwordField($model, 'password', array('class' => 'login password-field', 'placeholder' => 'Password')); ?> <?php echo $form->error($model, 'password'); ?> </div>



            <div class="login-actions">

                  <div style="-webkit-border-radius: 0 0 6px 6px;-moz-border-radius: 0 0 6px 6px;border-radius: 0 0 6px 6px;border-top: 1px solid #e5e5e5;background:#eee;padding: 0 18px 18px 0;"> <?php echo CHtml::submitButton('Sign In', array('class' => 'button btn btn-secondary btn-large')); ?>

                        <div class="clearfix"></div>





<?php $this->endWidget(); ?>

Does anyone know why this is not working?

Many thanks in advance.

Use inbuilt method for hashing password

$hash = CPasswordHelper::hashPassword($password);

// $hash is what we’ve saved to DB, $password is from login form

if (CPasswordHelper::verifyPassword($password, $hash)

// password is good


// password is bad

for more info reffere this Link

for this first download new released version and use it.

It’s very easy and reliable for hashing…

hope it may help u…

@kalpit: This will hardly help …

@auren27: This might sound stupid, but you have updated the fields for existing users in the database? Because I can spot no update mechanism in your authentication method.

i think you can write a wrong query…

please change the query like…

          $criteria = new CDbCriteria();

               $criteria->condition="t.user_login_id='".$this->username."'" AND   "t.user_password='".$this->password."'" ;

		$users = Users::model()->find($criteria);

i shared my code i hope so it’s may be some help

public function authenticate()


		//$email = $this->email;

		$criteria = new CDbCriteria();

		//$criteria->select = "t.*, CONCAT_WS(' ', t.`firstname`, t.`lastname`) AS `fullname`";

		$criteria->condition="t.username='".$this->username."'" AND "t.password='".$this->password."'" ;

		//$criteria->condition  = 't.username = \''.$this->username.'\' OR  t.`email` = \''.$email.'\'';

		//$criteria->condition  = ' t.user_type IN(\'admin\',\'superadmin\') AND(t.username= \''.$this->username.'\' OR  t.`email` = \''.$email.'\')';

		$users = Users::model()->find($criteria);

		if(!$users) {


		}else {

			$result= array(








			// $this->errorCode=$result;

			$systemPass = $users->password;

			$userPass 	= Yii::app()->getModule('api')->encrypting($this->password);

			if($users===null) {


			} else if($systemPass!==$userPass) {


			} else {

				//$this->email	= $users->email;

				$this->username	= $users->username;

				$this->password	= $users->password;


		 	 	//print Yii::app()->customer->id;

		 		//print Yii::app()->user->getId($users->id);

		 		$this->errorCode= self::ERROR_NONE;




		return !$this->errorCode;


Thank you for all the advice.

@kalpit: This project has been developed in version 1.1.13 and there is no time left in the project to upgrade the existing code to 1.1.14.

@Da:Sourcerer: You are correct, there is no ability to update records in the code. I was going to implement that but this login error appeared. I do have CRUD pages for my Users model though. You are able to update those.

@Ankit Modi: Thank you for sharing your code. It is a little different to what I need but I will use it in future.

It seems like the code is not able to match an encrypted version of the password that they enter in the form with the record in the database? Does the encryptionkey (that I have set in my config) need to be a particular length or format?

Many thanks

Ther should be virtually no limits regarding the encryption key. Given that sha256 is primarily a hashing algorithm, I wonder if it’s needed at all.

Another thing to look for: Are the password fields in your database of sufficient length? MySQL and other DBs are known to truncate data without warning if the field size is exceeded.

You got it!!

Yes, there was a length specified in the database field and was stripping 14 characters off the password. I have now changed the maximum length and it is working fine now.

Many thanks for your help.

Hey…thanks for sharing such complicated and interesting coding. Keep sharing such a unique coding with us.