Start learning with our library of video tutorials taught by experts. Get started
Viewers: in countries Watching now:
PHP is a popular, reliable programming language at the foundation of many smart, data-driven websites. This comprehensive course from Kevin Skoglund helps developers learn the basics of PHP (including variables, logical expressions, loops, and functions), understand how to connect PHP to a MySQL database, and gain experience developing a complete web application with site navigation, form validation, and a password-protected admin area. Kevin also covers the basic CRUD routines for updating a database, debugging techniques, and usable user interfaces. Along the way, he provides practical advice, offers examples of best practices, and demonstrates refactoring techniques to improve existing code.
Now that you understand the theory behind password hashing and salts we're ready to put the theory into practice and add password encryption to our CMS. Before we actually start encrypting passwords for our admins, let's create a little area that we can play with these a little bit and see how they work. We could take the time to actually create a new sandbox page and do that there. Instead I'm just going to do it right here in manageadmins.php. I'm just going to drop down to the bottom and right below my link for add a new admin, I'm going to put a hr tag and then underneath that, PHP tags.
And then in here, we can just do a little experimenting and look at it on that page. So to begin with, let's have our password equal to a string that we can see. We'll just make it secret. And then we're going to have to have our hash format. Now, the hash format that we're going to use is going to be "$2y$10$". That is what we're going to use for Blowfish. That basically tells PHP that we should use Blowfish. That's what the, 2y means, and 10 is the cost parameter.
That's essentially telling it how many times it ought to run the Blowfish hash. The more number of times we run it, the slower our Blowfish algorithm will be. It also gives us different results. Running it ten times versus 11 times makes a difference. Ten is a nice good number to use. So, so I recommend that to you unless you know that you need more. And then we're going to need to have our salt. Now, we're going to want to generate a random and unique salt, like we talked about. But for now, let's just start with a simple one that we can see and recognize. 22 characters or more. So, that's going to be the salt that we're going to use. Now we can just take a look at that.
The length of that. And we can call string. Len on the salt. And that'll tell us how large it is. Let's just go over and take a look at that. And you can see that it's 22 characters long. Now that's what Blowfish wants, it wants salts that are 22 characters or more. We can actually do some experimenting with that in a little bit and see what happens if it's longer or if it's shorter. And then of course we're going to take the format and the salt, and smash them together. So, format and salt is going to be equal to the hash format, and then append salt.
So then together, what are we going to do with those? We're going to pass those into our crypt. Function the password and our format and salt. So once we have that, then let's echo it. Let's do, echo let's first do br tag to keep it separate from the link up above and then echo our hash. Right, so let's see what happens when we apply the crypt function to secret using our format and salt that we've defined. That's what we get back.
This is the result of that operation. Notice that at the front of it is that format string and the salt. All right, that's right here at the very beginning, the actual encrypted portion is here, but it returns them both together. It just puts the salt at the beginning as part of the result. That's helpful for one really interesting reason. First of all, we can store them together in a single field of the database, we don't have to have one field for our hash and another field for the salt. But we also, then, can pass back in the hash itself as a salt.
And that's exactly what we'll do when someone tries to authenticate. Let's imagine that we're going to have a hash2, this is someone trying to log in, and we're going to take their password. This would be a form value this time, but we're going to go ahead and use secret again. or let's, let's go ahead and do it here this way. Secret and then instead of format and salt let's pass in the first hash. That's what we're going to pass in and then we'll take these two echo lines. This time we'll take a look at hash two. So, let's take a look at them they're exactly the same. So why is that? It's because this crypt function takes the first 22 characters that it gets here.
So in this case, we're only sending it 22 characters plus the hash format string as well. Here, when it gets the full hash, it also takes the hash format plus 22 characters, and it ignores the rest. What it uses for the salt is the salt portion here. So that's handy, because our hash contains the salt in it and it makes it easy for us, then, to compare. So, here we can see hash two and hash one are identical. Someone was able to correctly type in the correct password and it did work out just fine.
Now, we can try it with different lengths. Let's try or more, or more, or more, save it. Just come back and reload it. And you'll see that it's exactly the same. Even though it was a longer salt, it's still only used those first two and two characters. And for exactly the reason that we just saw, so that it can allow us to reuse that salt from the hash. Let's make it shorter though. Let's say salt 22 characters, take out the or more, now it's 16 characters, now notice that it pads it with some extra dollar signs.
It still gave us the same result though and that worked out, but let's try another example. Let's go back to or more. Let's take away just one character from it so now it's 21 characters long. Alright? Length 21. Look at my hashes. They're not the same. And that's because what's actually going on behind the scenes is that those characters, those 22 characters are being converted into bytes and bits that it's then working with. And if we have a wrong number, then we don't have enough, it doesn't have enough bytes and bits, and it compensates in strange ways. So, you want to make sure that you always have 22 characters or more in your salt, and then it will always work out.
Okay, so now we know how it works. You can play with it a little bit. If you want to try, you know, changing different hashes here, so now it's not secret, it's not spelled correctly, you see that you get a different result here. You can play around with it at little bit. You could try, changing the, the cost parameter, so that it's, 11. And then you'll notice that it's actually different here, right, versus ten. See, it gives a different result, depending on how many times we tell it that it ought to run the hashing function. Once you're done playing with that though, let's actually install this and let's use it. I'm going to take all of this code and I'm just going to erase it. So that we go back to our regular admin page.
There we go. Manage admins. And the first place that we want to install this code is going to be on new admin. Let me add an admin to the database. Instead of taking the plain text password that's sent in by a form and calling mysql_prep on it, instead we want to encrypt it. Now, we could just call crypt right here, but because we want to do all that with a salt and everything else, we're actually going to create our own function. Password_encrypt, and that's going to take care of everything that has to happen. So we'll have a plaint text password, pass it into password encrypt, and the result will be a hash. That same hash that we got back there, and that's what we'll store in the database.
So password encrypt is all we need. We don't need to call mysql_prep on it. The value that we get back is going to be suitable for MySQL. It's not going to have any single quotes in it that might cause a problem. Even if someone use that in their plain text version, once we encrypt it, it'll go away. Alright. So we're also going to need that password_encrypt to edit_admin so that when someone makes an edit here, same thing takes place. Again, takes the plain text password, turns it into a hash. So now let's write that function. Let's go over to our functions, and we know that we're going to need here function password_encrypt, and it's going to take an argument of password. So you can go and grab the other code that we used previously and paste it in here, it's going to be the same thing.
We're going to have the hash_format, we're going to have the salt_length and then I'm actually going to generate a random salt. Instead of using that string that we had, our set string, I'm going to have it generate something that's random and unique that we can use. That will be even better. And I'm going to tell it what the length ought to be, to make sure it's the right length. Then the salt we'll get attached to the hash format and we'll call crypt on it just like we did before. And then, of course, it will need to return that hash back from password_encrypt. Okay? So now we need another function and that's going to be generate_salt and it's going to take a length as an argument.
Again, I want to paste in some code. You can pause the movie if you need to copy it down. We're going to be creating a unique and random string. And this is the technique that I mentioned in the last movie that we're going to use. We're going to use mt_rand to get a random value, and pass that into unique id, that will guarantee that we get a unique id back. True tells it to be a little longer, a little more secure. And then we're going to pass that whole thing in to the md5 hash. Now the result of this is not 100 percent unique. Not 100 percent random. But it is going to be good enough for using, just for a salt. Then we're going to take a few extra steps here. We're going to make sure that it's base 64 encoded. The valid salt characters are going to be a to z, capital a to z, zero to nine, dot, and forward slash.
Those are the things that we're allowed to have in our salt. This will take care of most of it, with one exception. Base 64 in code returns a plus sign instead of the period. So we're going to then take another step here where we just replace all of the pluses with periods. And now we'll make sure that we have the right character that we need in our modified base 64 string. And then we'll call sub-string on it, that'll make sure it's the right length, and then that's the value that we'll return. So, we'll end up getting something that's unique, random, base 64 encoded, and is exactly the right length that we need. That's it.
Now, while we're here, let's also go ahead and write one more function, which is going to be called password_check. And if we pass in a password that someone submits from a form, and we pass in the existing_hash that's in the database, then we can see whether or not those match or not. Again, I'll paste in some code, hash equals, and it's the same thing we were doing, and we're taking that existing password with the existing_hash. It pulls the format and the salt from the beginning of that and uses that as the salt for this encryption. This hash here ought to be exactly equal to the existing_hash, and if they're exactly equal then we have a match, we return true otherwise we return false. So now, all we have to do is just call password check and we'll be able to tell, does a password, end up turning into our existing hash. So, let's save all that and let's try it out.
Let's go over here to manage admins, and let's just go to edit for my existing admin. And I'll put in a password of secret, edit the admin, admin updated. Now we can't see it here. We could go into MySQL and take a peak at it, but let's go ahead and just cheat a little bit. And let's just say in manage admins, right underneath username, let's do a br tag. And then we'll copy this. And we'll just ask it to output the hashed password. Now obviously we would not want to do this in real life, but it works for our purposes so that we can just get a peek at it. So there it is.
You can see that that's what it put in there and that's what it hashed. And if we add a new admin, let's call this one John Doe. His password will be hello everyone. Create the admin and you'll see that this is what his looks like. Notice that he has a unique salt at the beginning, it's different than what K (UNKNOWN) has. And then the result of the has is also there at the end and different. So now we have unique random salts stored in our database along with our hash. And we have the ability to check whether or not a login attempt matches or not.
We'll get to that login page in just a minute. First I want to talk about some of the new PHP password functions that are coming up soon.
Find answers to the most frequently asked questions about PHP with MySQL Essential Training.
Here are the FAQs that matched your search "":
Sorry, there are no matches for your search ""—to search again, type in another word or phrase and click search.
Access exercise files from a button right under the course name.
Search within course videos and transcripts, and jump right to the results.
Remove icons showing you already watched videos if you want to start over.
Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.
Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.