Securing your CodeIgniter passwords with bcrypt

Safe

I’ve applied a small modification to the Portable PHP password hashing framework, so it can be easily used in CodeIgniter projects. An example of using it to authenticate users:

$this->load->library( 'PasswordHash' );

    $query = $this->db->query("
        SELECT
            `user_id`,`password` AS `hash`
        FROM
            `user`
        WHERE   
            `username` = ". $this->db->escape($username) ."
        LIMIT
            1
    ");

    // check to see whether username exists
    if ( $query->num_rows() == 1 ) {
        $row = $query->row();

        if ( $this->passwordhash->CheckPassword( $password, $row->hash ) ) {
            return $row->user_id;
        }
    }

To generate a hashed password:

    $this->load->library( 'PasswordHash' );

    $password = ( isset( $_POST['password'] ) ? $_POST['password'] : '' );

    if ( $password ) {
        $hash = $this->passwordhash->HashPassword( $password );

        if ( strlen( $hash ) < 20 ) {
            exit( "Failed to hash new password" );
        }
    }

For more details, please check out the repository on GitHub: github.com/glenscott/passwordhash-ci

Glen Scott

I’m a freelance software developer with 18 years’ professional experience in web development. I specialise in creating tailor-made, web-based systems that can help your business run like clockwork. I am the Managing Director of Yellow Square Development.

More Posts

Follow Me:
TwitterFacebookLinkedIn

3 thoughts on “Securing your CodeIgniter passwords with bcrypt

  1. Brian G.

    If all you want to do is use bcrypt, you dont need to use the hashing framework. All you need to do is use PHP’s crypt function. You will of course need to be on PHP5.3+.

    Reply
  2. Techie Talks

    Thank you for sharing this library. Previously I was using pbkdf2 in my projects but somehow a local group of IT Professionals where I am active at convinced me with bcrypt though its one of my choice.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.