Password Hashing and Encryption In PHP; MD5, SHA1, SHA256, BCrypt

Password encryption and hashing in PHP, MD5, SHA1, SHA256, SHA512, bCrypt

Most modern PHP applications access important user information and store them in a database. For example, web app might have a registration system for new users. But how should you store usernames and passwords in the database?

You must always think about security. If passwords are stored in plain text, what happens if an attacker gains access to your database? He can easily read all of the users’ passwords. That’s why we use a technique called password hashing to prevent attackers from getting user passwords.

In this article you’ll learn how to store the passwords securely in the database so that, even if your database falls into wrong hands, no damage will be done.

What Is Password Hashing

Hashing is not a new concept. It has been in practical use for quite a long time. To understand hashing, think about fingerprints. Every person has a unique fingerprint. Similarly, each string can have a unique fixed-size “digital fingerprint” called a hash. For a good hashing algorithm, it’s very rare that two different strings will have same hash (called a collision).

The most important feature of hashes is that the hash generation process is one way. The one way property indicates that it’s impossible to recover the original text from its hash. Therefore password hashing perfectly suits our need for secure password storage. Instead of storing a password in plain text, we can hash the password and store the resulting hash. If an attacker later gains access to the database, he can’t recover original password from the hash.

But what about authentication? You can no longer compare the password entered by user in a login form with the hash stored in the database. You need to hash the login password and compare the result with the hash stored in the database.

How Hashing Is Done In PHP

There are different algorithms for generating hash of a text. The most popular ones are: MD5, SHA1, and Bcrypt. Each of these algorithms are supported in PHP. You really should be using Bcrypt, but I’ll present the other alternatives first because they help illustrate what you need to do to protect your passwords.

Let’s start with PHP’s md5() function which can hash passwords according to the MD5 hashing algorithm. The following example demonstrates the registration process:


<?php
$username = $_POST["username"];
$password = $_POST["password"];

// create connection to database
// ...

// sanitize the inputs
// ...

// create an MD5 hash of the password
$password = md5($password);

// save the values to the database
$sql = "INSERT INTO users (username, password) VALUES (:username, :password)";

$stmt = $db->prepare($sql);

$stmt->execute(array(
    ":username" => $username,
    ":password" => $password
));

And the following example shows the authentication process:


<?php
$username = $_POST["username"];
$password = $_POST["password"];

// create connection to database
// ...

// sanitize the input
// ...

// create an MD5 hash of the password
$password = md5($password);

// retrieve the information from the database
$sql = "SELECT * FROM users WHERE username=:username AND password=:password";
$stmt = $db->prepare($sql);
$stmt->execute(array(
    ":username" => $username,
    ":password" => $password
));

$row = $stmt->fetch();

In the above example, md5() creates a 128-bit hash out of the given password. It’s also possible to use sha1() instead of md5() which produces a 160-bit hash (which means there’s less chance of a collision).

If you generate an MD5 hash of the string “MySecretPassword” and output it to the browser, it will look like the following:

7315a012ecad1059a3634f8be1347846

“MySecretPassword” when hashed with SHA1 will produce the following output:

952729c61cab7e01e4b5f5ba7b95830d2075f74b

Never hash a password two times. It does not add extra security; rather, it makes the hash weak and inefficient. For example, don’t try to create an MD5 hash of a password and then provide it as input to sha1(). It simply increases the probability of hash collisions.

Taking Password Hashing to the Next Level

Researchers have found several flaws in the SHA1 and MD5 algorithms. That’s why modern PHP applications shouldn’t use these two hash functions. Rather, they should use hash algorithms from the SHA2 family like SHA256 or SHA512. As the name suggest, they produce hashes of length 256 and 512 bits. They are newer and considerably stronger than MD5. As the number of bits increase, the probability of a collision decreases. Either of the above two is more than sufficient to keep your application secure.

The following code shows how to use SHA256 hashing in PHP:


<?php
$password = hash("sha256", $password);

PHP offers the built-in function hash(). The first argument to the function is the algorithm name (you can pass algorithm names like sha256, sha512, md5, sha1, and many others). The second argument is the string that will be hashed. The result it returns is the hashed string.

Paranoia is Good – Using Salts for Added Security

Being paranoid about the security of your system is good. So, let’s consider another case here. You have hashed the user’s password and stored it in the database table. Even if an attacker gets access to our database, he won’t be able to determine the original password. But what if he checks all the password hashes with one another and finds some of them to be same? What does this indicate?

We already know two strings will have same hash only if both of them are same (in the absence of any collisions). So if the attacker sees same hashes, he can infer that the passwords for those accounts are same. If he already knows the password to one those accounts, then he can simply use that and gain access to all of the accounts with the same password.

The solution is to use a random number while generating the hash, referred to as salt. Each time we generate hash of a password, we use a random salt. You just need to generate a random number of a particular length and append it to the plain text password, and then hash it. In this way, even if passwords for two accounts are same, the generated hashes will not be same because the salts used in both cases are different.

The following demonstrates the use of salt:


<?php
define("MAX_LENGTH", 6);

function generateHashWithSalt($password) {
    $intermediateSalt = md5(uniqid(rand(), true));
    $salt = substr($intermediateSalt, 0, MAX_LENGTH);
    return hash("sha256", $password . $salt);
}

To create a salt we use the uniqid() function. The first argument is rand() which generates a random integer. The second argument is true to increase the chance of the generated number being unique.

To authenticate the user, you must store the salt used for hashing the password (It’s possible to store the salt in another column in same table where you have username and password stored). When the user tries to login, append the salt to the entered password and then hash it with the hash function.

Going Even Further: Using BCrypt

Learning about MD5/SHA1 and salts are good to gain an understanding of what’s needed for secure storage. But for implementing a serious security plan, Bcrypt is the hashing technique you should be using.

Bcrypt is based on the Blowfish symmetric block cipher. Ideally, we want a hashing algorithm to work very slowly for an attacker’s automated cracking attempts but not too slow that we can’t use it in real world applications. With Bcrypt, we can make the algorithm work n times slower while adjusting n in such a way that it won’t exceed our resources. Also, if you use Bcrypt then there is no need to store your salts in the database.

Let’s have a look at an example that uses the crypt() function to hash the password:


<?php
function generateHash($password) {
    if (defined("CRYPT_BLOWFISH") && CRYPT_BLOWFISH) {
        $salt = '$2y$11$' . substr(md5(uniqid(rand(), true)), 0, 22);
        return crypt($password, $salt);
    }
}

The above function checks whether the Blowfish cipher is available through the CRYPT_BLOWFISH constant. If so, then we generate a random salt. The requirement is that the salt starts with “$2a$” (or “$2y$” see this notice on php.net) to indicate the algorithm is Blowfish, followed by a two digit number from 4 to 31. This number is a cost parameter that makes brute force attacks take longer. Then we append an alphanumeric string containing 22 characters as the main portion of our salt. The alphanumeric string can also include ‘.’ and ‘/’.

Now it’s time to authenticate users:


<?php
function verify($password, $hashedPassword) {
    return crypt($password, $hashedPassword) == $hashedPassword;
}

Notice that we don’t need the salt for the password when authenticating because its part of the hashed output.

For more information on Bcrypt, and why should be using it, see Callum Hopkin’s article Why You Should Use Bcrypt to Hash Stored Passwords.

Summary

An important security measure to follow is always hash your users’ passwords before storing them in your database, and use modern hashing algorithms like Bcrypt, sha256, or sha512 to do so. When you do, even if an attacker gains access to your database, he won’t have the actual passwords of your users. This article explains the principles behind hashing, salts, and Bcrypt.

Article courtesy: Sandeep, PHPMaster.com

Advertisements