Programmers, don't store users' passwords!

It will take between 2 and 3 minutes to read this article

Photo by <a href="">Micah Williams</a> on <a href="">Unsplash</a> Photo by Micah Williams on Unsplash

It is quite likely if you've been using the internet for a few years, you've forgotten your password. Now most 'forgot your password' functions will send you a link to your email for you to create a new password. However, there are some which say "Your password is: FreddyLovesAvocado92". If this happens then there is only one way they can be sending you that information. They are storing your password, and what is worse it's almost certainly going to be in plain text. This means if there database is hacked into then all their users email addresses and passwords are exposed.

Please, for the love of all that is good, as a developer or programmer, please do not store your users' passwords in plain text. Even if you're beginning out in this field, please learn about hashing passwords. It's relatively simple and will be far more secure.


So we need to know what the user's password is but we can't store it in plain text? Correct - we will hash the password. To get our hash we will use a hash function. A hash function maps data of any length using a one-way mathematical algorithm to output a string of a fixed size.

For example: FreddyLovesAvocado92 (20 chars) when hashed might become $2a$10$CvQ7N/a1mYsmkB4RDhL0o.mE05MYJAwcIjYXTSFQt/Nt0qKzR3z2m (60 chars). Now no matter how long the password is it will always be 60 characters when hashed in this case. So 'supercalafragalisticexpialadocious' (40 chars) will become $2a$10$IidG7wJhjag2KZkd6YVV.eOM0os/GXzFOJOhRGwHSyL2tI/mUpf7G (60 chars).

So how might we achieve this in PHP? A function called 'bcrypt' exists in PHP which will hash your string without you having to build anything from scratch.

Now, something you need to realise with hashing is that the it doesn't return the same result twice. So, FreddyLovesAvocado92 won't always be $2a$10$CvQ7N/a1mYsmkB4RDhL0o.mE05MYJAwcIjYXTSFQt/Nt0qKzR3z2m, so we can't just check to see if the password the user is trying to log in with is directly equal to the one we have stored in the database. However PHP comes with a useful function called password_verify in which we can check to see if what the user is giving us as their password is correct or not.


Now to make this process more secure we can add a salt in. This means that we're not just converting a user's password but something additional too, which makes it much harder to hack.

To make this process even more secure you should really have a salt per user (which you would need to store in the database to retrieve every time you needed to check that user's password).

Published on Sun, 19 May, 2019