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

CSS3 Animation like Windows Phone Metro Tiles

CSS3 tile animation like windows phone

Windows phone is new to the market, but it hasn’t missed the chance to leave an impression with its cool new metro design. And what makes it alive are its Live tiles.

The live tiles, on the home screen are really a charm in the phone, all the information on one screen, no swiping pages.
What makes it more awesome is the cool new animation effects that the tiles bring while entering and exiting the homescreen. Its just so cool.
(Don’t have a windows phone? Never worry. Check a demo of the windows phone here online – http://www.windowsphone.com/en-us/cmpn/demo#home )

But what if you ever wanted to have such an animation in your website? maybe for a menu, or a list of products, or anything. It can be applied to anything grid-dy.

Sharing the pure-CSS3 code for a similar tile animation of a windows phone homescreen.

http://jsfiddle.net/yelton/Xwz7Q/

Have fun. If you like it, share it with others.

PHP (Database) Dependency Injection

PHP (Database) Dependency Injection

Dependency injection is the answer to more maintainable, testable, modular code.

Every project has dependencies and the more complex the project is the more dependencies it will most likely have.  The most common dependency in today’s web application is the database and chances are if it goes down the application will all together stop working.  That is because the code is dependent on the database server, which is perfectly fine.  Not using a database server because it could one day crash is a bit ridiculous.  Even though the dependency has its flaws, it still makes life for the code, and thus the developer, a lot easier.

The problem with most dependencies is the way that code handles and interacts with them. What I really mean is the problem is in the code and not the dependency.  If you are not using dependency injection, chances are your code looks something like this:

class Book {

	public function __construct() {

		$registry  = RegistrySingleton::getInstance();
		$this->_database = $registry->database;

		// or

		global $databaseConnection;
		$this->_database = $database;
	}

}

The book object now is given full access to the database once it is constructed.  That is good, the book needs to be able to talk to the database and pull data.  The problem lies in the way the book gained its access.  In order for the book to be able to talk to the database the code must have an outside variable named $database, or worse, it must have a singleton pattern class (registry) object containing a record for a database connection.  If neither of these exist the book fails, making the code far from modular.

This raises the question, how exactly does the book get access to the database?  This is where inversion of control comes in.

In Hollywood a struggling actor does not call up a director and ask for a role in his next film.  No, the opposite happens.  The director calls up the actor and asks him to play the main character in his next movie.  Objects are struggling actors, they do not get to pick the roles they play, the director needs to tell them what to do.  Objects do not get to pick the outside systems they interact with, instead, the outside systems are given to the objects.  Remember this as Inversion of Control.

This is how a developer tells his objects how to interact with outside dependencies:

class Book {

	private $_databaseConnection;

	public function __construct() { }

	public function setDatabaseConnection($databaseConnection) {
		$this->_databaseConnection = $databaseConnection;
	}

}
$book = new Book();
$book->setDatabase($databaseConnection);

This code allows for the book class to be used in any web application.  The Book is no longer dependent on anything other than the developer supplying a database shortly after object creation.

This is, at its finest, dependency injection.  There are two common ways of injecting dependencies.  The first being constructor injection and the second being setter injection.  Constructor injection involves passing all of the dependencies as arguments when creating a new object.  The code would look something like this:

$book = new Book($databaseConnection, $configFile);

There are some issues with constructor injection. First, the more dependencies a class has the messier the constructor becomes. Passing in three or four dependencies all in a constructor is extremely hard to read. Also, the less work a constructor does the better.

This leaves us with our second method of dependency injection, setter injection. A dependency is set by using a public method inside the class.

$book = new Book();
$book->setDatabase($databaseConnection);
$book->setConfigFile($configFile);

This is easy to follow, but it leads writing more and more code for your application.  When a book object is created three lines of code are required.  If we have to inject another dependency, a 4th line of code is now needed.  This gets messy quickly.

The answer to this problem is a container, which is class that is designed to hold, create, and inject all the dependencies needed for an application or class.  Here is an example:

class Container {

	public static $_database;

	public static function makeBook() {

		$book = new Book();
		$book->setDatabase(self::$_database);
		// more injection...

		return $book;
	}

}

And then:

$book = Container::makeBook();

All dependencies should be registered into the container object during run time.  This object is now the gateway that all dependencies must pass through before they can interact with any classes.  This is the dependency container.

The reason makeBook is a public static function is for ease of use and global access.   When I started this article off I made a reference to the singleton pattern and global access being a poor choices of code.  They are, for the most part.  It is bad design when they control access, but it is perfectly ok when they control creation.  The makeBook function is only a shortcut for creation.  There is no dependency what-so-ever between the book class and the container class.  The container class exists so we can contain our dependencies in one location and automatically inject those dependencies with one line of code creation.

The container class removes all of the extra work of dependency injection.

Before injection:

$book = new Book();

And now:

$book = Container::makeBook();

Hardly any extra work, but tons of extra benefits.

When test code is run, specifically unit tests, the goal is to see if a method of a class is working correctly.  Since the book class requires database access to read the book data it adds a whole layer of complexity.  The test has to acquire a database connection, pull data, and test it.  All of a sudden the test is no longer testing a single method in the book class, it is now also testing database.  If the database is offline, the test would fail.  This is far from the goal a unit test.

A way of dealing with this is just using a different database dependency for the unit tests.  When the test suite starts up a dummy database is injected into the book.  The dummy database will always have the data the developer expects it to have.  If a live database was used in a unit test the data could potentially change causing tests to unnecessarily fail.

The code is more modular because it can dropped into any other web application.  Create the book object and inject a database connection with $book->setDatabase().  It does not matter if the database is in Registry::Database, $database, or $someRandomDatabaseVarible.  As long as there is a database connection the book will work inside any system.

The code is more maintainable because each object is given exactly what it needs.  If separate database connections are required between different instances of the same class then there no extra code needed inside the class what-so-ever.  Give book1 access to database1 and book2 access to database2.

Container::$_database = $ourDatabaseVarForDB1;

$book1 = Container::makeBook();
$book2 = Container::makeBook();
$book2->setDatabase($database2);

Dependency injection really is the answer to more maintainable, testable, modular code.