Tuesday, November 27, 2012

New, Simple, Password Hashing API Coming in PHP 5.5


Everyone who writes web applications should know by now that hashing passwords is a necessity. Storing password in plain text in the database or using a simple MD5 or SHA256 has is simply not enough in the face of video cards that can make millions of guesses per second. Unfortunately, it's also a reality that we still see many high use, high profile sites either not hashing passwords at all or doing so in insecure ways.

Thankfully, PHP has come to the rescue with new password hashing functions built into 5.5 alpha. Now, properly hashing passwords couldn't be simpler:

$hash = password_hash($password, PASSWORD_DEFAULT); 
 
The above code creates a password hash using the default algorithm (bcrypt), the default load factor (10), and a random, automatically generated, salt. The algorithm and salt will be part of the resulting hash so there's no worries about what to do with them when you stick them in the database.

If you don't want to stick with the defaults (which might change in the future) you don't have to and you can specify both the hashing algorithm and the load very easily:

$hash = password_hash($password, PASSWORD_BCRYPT, ['cost' = 12]); 

In the example above, we've specified that the hashing algorithm used is the BCRYPT algorithm and that the load is 12 instead of 10. This gives us a lot of flexibility when we're hashing our passwords and allows for fairly easy integration with your current security setup.

Verifying passwords is almost the same as it's always been. In fact, if anything, I think it's a little cleaner and easier


// Get the password from the user and the hash from the DB

if(password_verify($password, $hash){
    // password passed verification
}
else{
    // password failed verification
}

The function returns true or false depending on if you have a match and makes creating and verifying secure hashes amazingly simple.

One thing that should also be noted is that you get the benefit of automatic hashing algorithm upgrades. When/if the PHP developers decide to change the default algorithm used to hash passwords to something other than BCRYPT, your new hashes will automatically be upgraded when you upgrade your PHP installation without the need to rewrite any code.

Overall, this is a really strong development and shows why PHP should still be a strong contender for a place in any web developers toolbox. And, with as simple as hashing and hash verification is, we'll hopefully start to see even inexperienced web developers start to take password security more seriously and avail themselves of, what I consider, one of the languages best new features.

No comments: