What is password hashing?
It turns a string (of any length) to a fixed length "fingerprint" that cannot be reversed. For example, my password is "i1love2coding3", when hashed, it can be converted to a 60 character "ytwqwxpbx1oxbfvmpoaafckmat2zkdsjaxs..." which will be stored to the database.
Why do we have to hash passwords?
I think the main reason why we have to hash passwords is to prevent passwords from being stolen or compromised.
I know that some PHP frameworks or CMS already provide this functionality, but I believe that it is important for us to know how its implementation can be made.
|Saved password was salted and hashed.|
We are going to use a Portable PHP Password Hashing Framework called phpass (pronounced "pH pass") recommended by a lot of forums and is used by some famous Web applications like phpBB3, WordPress, Drupal, Vanilla, etc.
This post will focus and provide you a quick grasp and basic idea on how to salt, hash and store passwords in a MySQL database. This is essential to your PHP login script.
Let's CodeOur SQL table structure looks like this:
CREATE TABLE IF NOT EXISTS `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `email` varchar(32) NOT NULL, `password` char(60) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
libs/PasswordHash.php - our password framework file, yes, it is just this one file. You can download it here.
libs/DbConnect.php - configuration to be connected to database.
register.php - The user registration page, this is where we are going to save the user's password. On this example web app, we require these two fields only during registration.
login.php - the user login page, we are going to check if the users's password is valid or not .
css/style.css - just for some styling.
|Just a sample HTML5 validation.|
|After successful registration.|
|Our database will have the record. |
Notice the password field, it was hashed.
|Our login page.|
|Just an example HTML5 validation during login.|
|Login with wrong credentials.|
|After login with correct username and password.|
- We should never store passwords as plain text.
- Add a long, unique random salt to each password you store so that brute force attacks will be a waste of time.
- If you want to have a deeper understanding and learn more techniques, I highly recommend reading the documentation, it's kinda long, but it's worth your time!
- Salted Password Hashing - Doing it Right
- How to store salt?
- Use bcrypt.
Please note that password hashing is often wrongly referred to as "password encryption". Hashing is a more appropriate term since encryption is something that is supposed to be easily reversible. ~ phpass
If there's something you want to add, something wrong, or any questions, please let me know in the comments. Thanks a lot!
For FREE programming tutorials, click the red button below and subscribe! :)