3

Need help because i'm still new to Yii2. I want to encrypt the password before saving it to the database. So i'm using sha1 but the problem is that the password field in the form has contents when i apply this line of code in the controller shown below.

$model->password = sha1($model->attributes['password']);

This is the Controller create method:

public function actionCreate()
{
    $model = new Employeeinformation();

    //$model->password = sha1($model->attributes['password']);

    $model->created_date = date('Y-m-d H:i:s');

    if ($model->load(Yii::$app->request->post()) && $model->save()) {
        return $this->redirect(['view', 'id' => $model->employee_id]);
    } else {
        return $this->render('create', [
            'model' => $model,
        ]);
    }
}

This is the form:

<div class="employeeinformation-form">

<?php $form = ActiveForm::begin(); ?>

<?= $form->field($model, 'employee_id')->textInput(['minlength' => true, 'maxlength' => true]) ?>

<?= $form->field($model, 'password')->passwordInput(['maxlength' => true]) ?>

<?= $form->field($model, 'last_name')->textInput(['maxlength' => true]) ?>

<?= $form->field($model, 'first_name')->textInput(['maxlength' => true]) ?>

<?= $form->field($model, 'hired_date')->widget(\yii\jui\DatePicker::classname(), [
    'language' => 'en',
    'dateFormat' => 'yyyy-MM-dd',
]) ?>



<div class="form-group">
    <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>

<?php ActiveForm::end(); ?>

Screenshot of my problem:

http://i.imgur.com/YTDW1Ud.png

Thank you in advance.

Scott Arciszewski
  • 33,610
  • 16
  • 89
  • 206
WaduNoop
  • 65
  • 1
  • 2
  • 14
  • possible duplicate of [Secure hash and salt for PHP passwords](http://stackoverflow.com/questions/401656/secure-hash-and-salt-for-php-passwords) – Nathan Tuggy Sep 02 '15 at 03:17
  • This is the browser auto-fill in action. Try changing the attribute name to something other than "password" such as "pwd" and see if the auto-fill still there. – Osh Mansor Sep 02 '15 at 04:21
  • Also please read this http://php.net/manual/en/book.password.php – Sergey Sep 02 '15 at 05:51
  • @OshMansor. I tried changing the attribute name but the auto-fill is still there. – WaduNoop Sep 02 '15 at 06:00

6 Answers6

16

I want to encrypt the password before saving it to the database.

No you don't. Well, you might think you want to encrypt the password, but if you're trying to protect users you actually want to hash the password, not encrypt it.

SHA1 doesn't provide encryption, it's a hash function. This is a very common misconception. You can learn more about basic cryptography terms and concepts at the linked blog post.

More importantly: You don't want a fast hash like SHA1 for passwords. Use password_hash() and password_verify() and you'll have secure password storage. You don't even need to particularly care what these functions do internally to use them correctly.

public function actionCreate()
{
    $model = new Employeeinformation();
    $post = Yii::$app->request->post();

    if ($model->load($post)) {
        $model->password = password_hash($model->password, PASSWORD_DEFAULT);
        $model->created_date = date('Y-m-d H:i:s');
        if ($model->save()) {
            return $this->redirect(['view', 'id' => $model->employee_id]);
        }
    }
    return $this->render('create', [
        'model' => $model,
    ]);
}

When employees login, you just need to do this:

if (password_verify($request->password, $storedEmployeeData->hashed_password)) {
    // Success
}
Scott Arciszewski
  • 33,610
  • 16
  • 89
  • 206
  • 1
    Whoa, thank for the information dude. I really admit that i misunderstood the difference of hash and encryption. I will apply your advises to improve my coding. Thanks a lot !!!!! – WaduNoop Sep 03 '15 at 03:42
  • Glad to hear it. Please pass this knowledge on. :) – Scott Arciszewski Sep 03 '15 at 03:43
  • 1
    @Scott Arciszewski hit the nail on the head. Do not try to do cryptology, many very smart people spend a lot of time working it out; use what is already available via the password_*() methods. – David J Eddy Jul 07 '16 at 15:36
8

Yii2 comes with user module in advanced setup. See how it store user passwords in encrypted way.

You can use setPassword() method in User Model to get hashed passwords.

public function setPassword($password)
{
    $this->password_hash = Yii::$app->security->generatePasswordHash($password);
}

and call this method before saving model data.

public function signup()
{
    if ($this->validate()) {
        $user = new User();
        $user->username = $this->username;
        $user->email = $this->email;
        $user->setPassword($this->password);
        $user->generateAuthKey();
        if ($user->save()) {
            return $user;
        }
    }
    return null;
}

Also look at the Yii2 doc for passwords and authentication.

ankitr
  • 5,992
  • 7
  • 47
  • 66
0

The content for password is there because you set the attribute before sending the data through the save (and validate) method.

If you like to do it in the controller, you can do it as the following:

public function actionCreate()
{
    $model = new Employeeinformation();

    if ($model->load(Yii::$app->request->post())){

        $model->password = sha1($model->password);
        $model->created_date = date('Y-m-d H:i:s');
        if ($model->save())
            return $this->redirect(['view', 'id' => $model->employee_id]);
    } 
    return $this->render('create', [
        'model' => $model,
    ]);

}

Another way, is to do the password hashing in the beforeSave method of the Employeeinformation model (add this method inside the model class):

public function beforeSave($insert) 
{
    if(isset($this->password))
        $model->password = sha1($model->password);
    $model->created_date = date('Y-m-d H:i:s');

    return parent::beforeSave($insert);
}

If done using the beforeSave method, these two lines in the controller code can be removed as they are no longer necessary:

$model->password = sha1($model->password);
$model->created_date = date('Y-m-d H:i:s');

However, referring to http://www.yiiframework.com/doc-2.0/guide-security-passwords.html, it is not recommended to use md5 or sha1 for password encryption. Yii2 provide two helper functions to generate & verify password.

Use this to encrypt password:

$hash = Yii::$app->getSecurity()->generatePasswordHash($password);

And to verify it:

if (Yii::$app->getSecurity()->validatePassword($password, $hash)) {
    // all good, logging user in
} else {
    // wrong password
}

This is a better choice than sha1 that is used in the original code you posted.

Osh Mansor
  • 1,232
  • 2
  • 20
  • 42
0

you can look at User model for example, there are method setPassword()

public function setPassword($password) { $this->password_hash = Yii::$app->security->generatePasswordHash($password); }

this is how to you set password on database, and also it's already encrypt by yii2 encription

rahmatheruka
  • 57
  • 1
  • 10
-5
$password = md5($password);

Best way to handle, make sure to correlate this to the login screen to check

$passwordentered = md5($passwordentered);
if ($passwordentered = "Correct"){
"Grant Access"
}

Hope this helps.

Dylan_H
  • 1
  • 4
-6

In your model add:

public function beforeSave()
    {
        $this->password=md5($this->password);
        return true; 
    }

Now add this to your controller:

$model->password = md5($model->password);
Ankush Rishi
  • 2,861
  • 8
  • 27
  • 59