PHP’s password_hash() and password_verify()

Recently, I needed a way to hash passwords for a user system I am putting together. I needed it to be simple, easy to implement, and preferably, native to the environment I was using (php). I know that MD5 is way out of date, and the various SHA1, SHA256 implementations were weak. With that in mind, I am well aware of the negatives and weaknesses of trying to roll my own password hashing / encryption methods, so I took to the PHP Docs and came across password_hash() and it’s counterpart, password_verify().

This post wont cover any DB transactions in terms of storing or fetching, that’s beyond the scope I feel, and it doesn’t cover the algorithm

password_hash()

This function is built into PHP as of 5.5 and works really well for most applications and security requirements. In addition, it takes 2 arguments and 3rd optional argument based on the type of method you pass:

  1. The password string.
  2. The password algorithm method – usually either PASSWORD_DEFAULT or PASSWORD_BCRYPT
  3. Optional – http://php.net/manual/en/password.constants.php

 

password_verify()

This function goes hand in hand with the password_hash() function. It takes 2 arguments:

  1. The password string to be checked.
  2. The existing password string (presumably from your DB).

 

How did I implement it?

In my registration process, I ingested the form’s password field (I use Slim for most of my development), and began the process.

$password = password_hash($_POST['password_field'], PASSWORD_DEFAULT);

I stored $password into my user table and a hash that looked something like this was produced:

It’s important to note that the column in my database uses ‘text’ – the hashes can get really long pending the algorithm you utilize.

Then, in my login process, I fetch the hashed password (this varies depending on how you validate a user’s login attempt):

if ( password_verify( $_POST['login_password_field'], $dbRow['password'] )) {

    //The password provided by the login form matched the password stored in the DB
}
And with that, I was able to easily and painlessly implement a fairly sufficient method to securing my user’s password.
adam Written by:

Be First to Comment

Leave a Reply