PHP Bytesize : Passsword Hashing

Part of a new series to increase the frequency of the posts here at RecursiveIterator, I’m going to start posting shorter quick tip posts.

Hashing. Encrypting. Cyphering. These are music to the media’s ears when they think of programmers and hackers.

In reality hashing is generally used for data that we want to simply do a comparison with, and we’re not actually too bothered about the original data.

Consider the humble password, when a user enters it, we need to make sure that the password matches the password for the username in the DB.

We don’t strictly care what that password is, just the match.

Next let’s imagine a hacker makes off with the user table somehow, with the passwords. If these are stored as entered, then they can quite easily login and access that users account, make changes and essentially balls things up for everyone. Bad times eh?

So what we want is to hash the password, store this in the DB (so that the password is all but useless to an intruder), and have a process that hashes the input before doing a comparison.

For example let’s say I has a password, such as ‘password’ (unique I know!), upon adding this to the DB we convert it to, lets go with ‘p455w0rd’.

When I login, I enter ‘password’, this is run through the converting function before comparing the result with what is in the DB.

So say ‘Johnny No Legs’ the devlish hacker, with eye-patch and two wooden legs, gains access to our DB and gets these details.

With a wry grin he enters the password ‘p455w0rd’ and slams his mouse button down on the login button.
Our system converts the entered value, and ah ha!

The result doesn’t match! Foiled again ‘Johnny’.

Now there are multiple ways of achieving this, however did you know that PHP has a built in function for this?

The beauty of this is, as PHP continues development through versions, improvements to this function won’t require you to refactor your code.
PHP 7 for instance will have an update to how secure this is behind the scenes, without you having to modify your code.