How to create a secure password hashing function in PHP

Post Reply
User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

How to create a secure password hashing function in PHP

Post by Neo » Fri Feb 19, 2010 10:54 pm

This function returns a more secure password hash by using SHA1 encryption algorithm with the combination of using a salt,returning a salted hash. Salt is a random bit of data, consisting of upper and lower-case letters with the combination of numbers and special characters to be included in the string you want to hash so we can avoid the possibility of dictionary hacks. If you are using PHP 5.12 or above, you might want to look at SHA2 (sha256,sha384,sha512) encryption algorithm.

The function:

Code: Select all

    function password_hash($username,$password)
    {
    $salt = “123456789ThisIStheSalt9876543210?;
    return sha1($username . $password . $salt );
    } 
In this function, I had used a 32-character,combination of upper and lower-case letters and numbers salt. You can change it to whatever random string of data you have come up with.You can also use special characters too!(!@#$,etc.). I have included the username in the parameter of the function so the string to be hashed will be more longer (username + password + salt).

Usage:

Code: Select all

    if($_POST['register_button'])
    {
    /* Clean first your post variables against SQL injection and cross site scripting attacks, cleaning function is not included in this tutorial */

    // hash the password using the inputed username and the password
    $hashed_password = password_hash($username , $password);

    //proceed to inserting details in your database
    } 
For example, when a user register on your page, his username is “myusername” and password is “mypassword”, we will take his username and password and hash it using the function. The outcome of the hash will be “d6bbfc3af54c4736839fd339715b6698fb7d23e2? . Isn’t that more secure than storing the plain-text password in your database?Yes it is. Then you’re ready to store the generated hash in the password field of your database.

Code: Select all

    if($_POST['login_button'])
    {
    /* Clean first your post variables against SQL injection and cross site scripting attacks, cleaning function is not included in this tutorial */

    // hash the password using the entered username and the password
    $hashed_password = password_hash($username , $password);

    //proceed to check if username and password matches in your database

    } 
When a user logs-in, we will take his username and password and hash it again using the same function.Then we will proceed to validate the username and the hashed password with the details stored in the database.
Post Reply

Return to “PHP & MySQL”