如何在 cakephp 2.x 版本中加密密码



大家好,我正在使用cakephp 2.x,因为我是这里的新手,我需要在密码存储到数据库之前加密我的密码

User.ctp : 我像这样发帖是为了发帖

<?php
  echo $this->Form->input('password',array('type'=>'password','label'=>false,'div'=>false,'class'=>'form-control','id'=>'password'));
?>

控制器:

public function setting()
{
    $this->layout='setting_template';
    if($this->Session->read('username')==""){
        $this->redirect(array('action' => 'user_login'));
    }
    elseif ($this->Session->read('username') == "admin" )
    {
        if($this->request->is('post'))
        {
            $this->data['password'] = encrypt($this->data ['password']);
            if ($this->Login->save($this->request->data)) {
                $this->Session->setFlash('The user has been saved');
                $this->redirect(array('action' => 'setting'));
            } else {
                $this->Session->setFlash('The user could not be saved. Please, try  again.');
            }
            }
        $opp=$this->Login->find('all');
        $this->set('login',$opp);
    }
    else{
        echo "<script type='text/javascript'> alert('Permission Denied');    </script>";
        $this->redirect(array('action' => 'index'));
    }
}

登录控制器:

public function login()
{
$this->layout='login_template';
if($this->data)
{
$this->Session->write('id',$this->data['Login']['id'] );
$results = $this->Login->find('first',array('conditions' =>  array('Login.password' => $this->data['Login']['password'],'Login.username'  => $this->data['Login']['username'])));
$this->Session->write('name',$results['Login']['name']);
if ($results['Login']['id'])
 {
 $this->Session->write($this->data['Login']['username'].','. $this->data['Login']['password']);
   $this->Session->write('username',$this->data['Login']['username']);
   $this->redirect(array('action'=>'index'));
   }
  else
  {
   $this->Session->setFlash("error");
 }
}

如何加密密码文件以及如何使用模型

当你使用CakePhp时,请遵循框架的最佳实践。

创建新用户记录时,您可以在 之前使用适当的密码哈希器保存模型的回调 .class:

App::uses('SimplePasswordHasher', 'Controller/Component/Auth');
class User extends AppModel {
   public function beforeSave($options = array()) {
        if (!empty($this->data[$this->alias]['password'])) {
        $passwordHasher = new SimplePasswordHasher(array('hashType' => 'sha256'));
            $this->data[$this->alias]['password'] = $passwordHasher->hash(
            $this->data[$this->alias]['password']
            );
        }
        return true;
    }
 }

在调用 $this->Auth->login() 之前,您无需对密码进行哈希处理。各种身份验证对象将单独对密码进行哈希处理。

如果您使用与User不同的模型进行身份验证,则需要在 AppController 中定义它。在你的情况下,你需要在AppController中做这样的事情:

$this->Auth->authenticate = array(
'Form' => array('userModel' => 'Login')
);

如果您想对密码进行哈希处理,请尝试以下操作:

$hashedPassword = AuthComponent::password('original_password');

看这里:Cakephp密码散列。

最新更新