Search code examples
phpcodeignitersecuritypassword-protectionpassword-encryption

How to generate password salt with codeigniter


Sorry for being new in php programming, in my old project I use MD5 to encrypt the password, however, it is not secure enough and I found some resource on the internet suggest using password salt instead.

The problem is , I am using codeigniter, is there any helper/ library for this purpose / how to change my old code to support the generation of the password salt?

Thanks for helping. I am using PHP 5.2

And here is the old code to validate, while the user account generate by storing the md5($password);

function validate_credentials() {
        $this->load->model('Secure_model');

        $username = $this->input->post('username');
        $password = md5($this->input->post('password'));

        $is_valid = $this->Secure_model->validate('customer', $username, $password);

        if ($is_valid) {
            $data = array(
                'user_id' => $this->get_user_id($username),
                'user_name' => $username,
                'is_logged_in_user' => true
            );
            $this->session->set_userdata($data);
            redirect('profile');
        } else {
            $data['message_error'] = TRUE;
            $data['main_content'] = 'front/login';
            $this->load->view('front/includes/template', $data);
        }
    }

Solution

  • If you are really stuck with PHP 5.2 your best bet will propably be the phpass library, because there is no PHP support of the BCrypt algorithm.

    PHP versions 5.3 and later will have native support of BCrypt, so you can use the PHP function password_hash() to hash a password. There is a compatibility pack for versions before 5.5.

    // Hash a new password for storing in the database.
    // The function automatically generates a cryptographically safe salt.
    $hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT);
    
    // Check if the hash of the entered login password, matches the stored hash.
    // The salt and the cost factor will be extracted from $existingHashFromDb.
    $isPasswordCorrect = password_verify($password, $existingHashFromDb);
    

    In every case you are doing right with discarding MD5 and switching to another algorithm. Make sure that you use an algorithm with a cost factor like BCrypt or PBKDF2, fast algorithms like SHA* are not appropriate to hash passwords. Salting is mandatory, though the salt can be stored in the database, it fulfills its purpose even if it is known.