Password Hashing in CodeIgniter

In old days, we were using MD5 and SHA1 algorithms to encrypt the password. But those algorithms are pretty old and not reliable now a days (So many websites are still using SHA1 and its more reliable than MD5). Its an age of advance encryption, and need to secure our password with some advance techniques. Password hashing is provided by PHP.

Password hashing in PHP:

In PHP, php will generate the unique hash for your password every time so you need not to use your own salt and store it in database. I used this core PHP function for password hashing in my codeigniter code. And it is working like charm.

Function in Helper :

/**
 * This function used to generate the hashed password
 * @param {string} $plainPassword : This is plain text password
 */
if(!function_exists('getHashedPassword'))
{
    function getHashedPassword($plainPassword)
    {
        return password_hash($plainPassword, PASSWORD_DEFAULT);
    }
}

/**
 * This function used to generate the hashed password
 * @param {string} $plainPassword : This is plain text password
 * @param {string} $hashedPassword : This is hashed password
 */
if(!function_exists('verifyHashedPassword'))
{
    function verifyHashedPassword($plainPassword, $hashedPassword)
    {
        return password_verify($plainPassword, $hashedPassword) ? true : false;
    }
}

 Registration Code :

Controller function :

/**
 * This function is used to add new user to the system
 */
function addNewUser()
{
    if($this->isAdmin() == TRUE)
    {
        $this->loadThis();
    }
    else
    {
        $this->load->library('form_validation');
       
        $this->form_validation->set_rules('fname','Full Name','trim|required|max_length[128]|xss_clean');
        $this->form_validation->set_rules('email','Email','trim|required|valid_email|xss_clean|max_length[128]');
        $this->form_validation->set_rules('password','Password','required|max_length[20]');
        $this->form_validation->set_rules('cpassword','Confirm Password','trim|required|matches[password]|max_length[20]');
        $this->form_validation->set_rules('role','Role','trim|required|numeric');
        $this->form_validation->set_rules('mobile','Mobile Number','required|min_length[10]|xss_clean');
            
        if($this->form_validation->run() == FALSE)
        {
            $this->addNew();
        }
        else
        {
            $name = ucwords(strtolower($this->input->post('fname')));
            $email = $this->input->post('email');
            $password = $this->input->post('password');
            $roleId = $this->input->post('role');
            $mobile = $this->input->post('mobile');
             
            $userInfo = array('email'=>$email, 'password'=>getHashedPassword($password), 'roleId'=>$roleId, 'name'=> $name,'mobile'=>$mobile, 'createdBy'=>$this->vendorId, 'createdDtm'=>date('Y-m-d H:i:sa'));
                
            $this->load->model('user_model');
            $result = $this->user_model->addNewUser($userInfo);
               
            if($result > 0)
            {
                $this->session->set_flashdata('success', 'New User created successfully');
            }
            else
            {
                $this->session->set_flashdata('error', 'User creation failed');
            }
             
            redirect('addNew');
        }
    }
}

In above controller, getHashedPassword is a function which create hashed password.

Model function :

/**
 * This function is used to add new user to system
 * @return number $insert_id : This is last inserted id
 */
function addNewUser($userInfo)
{
    $this->db->trans_start();
    $this->db->insert('tbl_users', $userInfo);
      
    $insert_id = $this->db->insert_id();
        
    $this->db->trans_complete();
        
    return $insert_id;
}

 

Login Code :

Controller function :

/**
 * This function used to logged in user
 */
public function loginMe()
{
    $this->load->library('form_validation');
        
    $this->form_validation->set_rules('email', 'Email','required|valid_email|max_length[128]|xss_clean|trim');
    $this->form_validation->set_rules('password', 'Password', 'required|max_length[32]|');
        
    if($this->form_validation->run() == FALSE)
    {
        $this->index();
    }
    else
    {
        $email = $this->input->post('email');
        $password = $this->input->post('password');
            
        $result = $this->login_model->loginMe($email, $password);
            
        if(count($result) > 0)
        {
            foreach ($result as $res)
            {
                $sessionArray = array('userId'=>$res->userId,                    
                                      'role'=>$res->roleId,
                                      'roleText'=>$res->role,
                                      'name'=>$res->name,
                                      'isLoggedIn' => TRUE
                                );
                                  
                $this->session->set_userdata($sessionArray);
                 
                redirect('/dashboard');
            }
        }
        else
        {
            $this->session->set_flashdata('error', 'Email or password mismatch');
             
            redirect('/login');
        }
    }
}

Model function :

/**
 * This function used to check the login credentials of the user
 * @param string $email : This is email of the user
 * @param string $password : This is encrypted password of the user
 */
function loginMe($email, $password)
{
    $this->db->select('BaseTbl.userId, BaseTbl.password, BaseTbl.name, BaseTbl.roleId, Roles.role');
    $this->db->from('tbl_users as BaseTbl');
    $this->db->join('tbl_roles as Roles','Roles.roleId = BaseTbl.roleId');
    $this->db->where('BaseTbl.email', $email);
    $this->db->where('BaseTbl.isDeleted', 0);
    $query = $this->db->get();
        
    $user = $query->result();
        
    if(!empty($user)){
        if(verifyHashedPassword($password, $user[0]->password)){
            return $user;
        } else {
            return array();
        }
    } else {
        return array();
    }
}

In above model, verifyHashedPassword function is used to match the password with hashed password.

Hashing with Bcrypt algorithm :

Password hashing with Bcrypt is more secured than normal hashing. bcrypt uses the Eksblowfish algorithm to hash passwords.

Reference:
Create hash password
Verifies that a password matches a hash