Password hashing in PHP

Been working on a web site this past week that requires users to login for access to member information. In this case I’m storing the user information, along with other info, in a MySQL database. For my initial testing I was just storing the user password as text in the database but I didn’t want to do this for the real site. This being a new area for me I did some digging around and found a great write up on encrypting passwords for storing in a database using PHP.

There are two examples given on the site, mainly encrypting the password on it’s own using md5 or sha1, or by adding a salt string to the password so if people do get access to the database, even duplicate passwords will not look the same making it one more step that someone needs to crack the passwords. While I’m not looking to secure any company secrets or anything I just think it’s good practice to do something with a little security.

Here’s the code sample from the site as a reference, I’d highly recommend reviewing the entire post on Password Hashing for more details and explanations.

<?php
define(‘SALT_LENGTH’, 9);
function generateHash($plainText, $salt=null)
{
      $salt = substr(sha1(uniqid(rand(), true)), 0, SALT_LENGTH);
}
else
{
     $salt=substr($salt, 0, SALT_LENGTH);
}
return $salt . sha1($salt . $plainText);
}
?>

This function can then be called with a single variable, the password to be encrypted, and it will return the encrypted password:

$passwordhash=generateHash($password);

To validate the password, the function is called with both the user supplied password to validate followed by the encrypted password hash stored in the database:

$valpassword=generateHash($password, $passwordhash);

The function call above will only encrypt the user supplied password to be validated using the same “salt” that the original password was encrypted with…you can then compare the two to validate the user supplied password matches the password hash stored in the database.

Advertisements
Explore posts in the same categories: PHP, Tech

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: