If you want to build a user-management system – or work on someone else’s – you should know a few basics about how passwords are encrypted or hashed. In other words, how are they made safe for storage?
What is a Hash?
Before a password is stored, it is typically converted into a “hash.” This isn’t technically a form of encryption, because it is a one way process. Once a password has been hashed… there’s no going back.
For example, if I hash the phrase “Bananas,” I might get back this garbled mess of characters – “1ee31b77d0697c36914b99d1428f7f32.”
The reason we do this is so that someone who views the database – a hacker or maybe a dishonest systems adminstrator – can’t figure out your password. He or she will see the hash and have no idea what the password is.
The script that checks your password when you log in knows how the hash was created – so it can recreate that hash if you give it the same password. The hash it creates based on your input can then be checked against the one in the database to see if you entered the real password.
Ok, How Do We Create a Hash?
There are two major functions for creating hashes in php – md5() and crypt().
md5 is the simpler function, so we’ll start there. You simply call the function like so…
This returns the encrypted hash. If you called md5(“Bananas”), you would always get “1ee31b77d0697c36914b99d1428f7f32” back as a result. You would then store that phrase in the database to check the password in the future.
Crypt is a bit more complicated. With md5, you always get the same result. With crypt, you can use different encryption keys or “salts” to get different results. You can encrypt something with crypt like this…
crypt(“Password String”, “Salt”);
If you do not provide a salt or encryption key, them PHP creates one for you. This changes the way the word is hashed. So if you called crypt(“Bananas”) twice, you would get two different results. Here’s some extra reading on how to use crypt to hash and encrypt a password in PHP.
So Which is Better?
That’s debateable. In most cases, crypt uses the same hashing algorithm that md5 does. Neither is necessarily “stronger” than the other.
The one advantage that crypt does has is that it can a different encryption key or salt each time. The same password can have a different hash if it is created with a different salt.
Therefore it is near impossible to create a dictionary of known hashes. With md5, this can be done easily – because each password phrase has only one possible hash value.
A dictionary like this would make a hacking attempt much easier than if the computer had to physically hash and check each possible phrase. Here’s some more reading on the difference between md5 and crypt.
Good luck hashing, and remember – the best way to learn php is to try new things. So go practice.