Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Adding password encryption to CMS

From: PHP with MySQL Essential Training

Video: Adding password encryption to CMS

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.

Adding password encryption to CMS

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 kskoglund 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.

Show transcript

This video is part of

Image for PHP with MySQL Essential Training
PHP with MySQL Essential Training

131 video lessons · 38041 viewers

Kevin Skoglund
Author

 
Expand all | Collapse all
  1. 4m 8s
    1. Welcome
      1m 0s
    2. Using the exercise files
      3m 8s
  2. 15m 6s
    1. What is PHP?
      3m 52s
    2. The history of PHP
      2m 51s
    3. Why choose PHP?
      4m 10s
    4. Installation overview
      4m 13s
  3. 54m 53s
    1. Overview
      2m 33s
    2. Working with Apache Web Server
      6m 56s
    3. Changing the document root
      7m 24s
    4. Enabling PHP
      6m 16s
    5. Upgrading PHP
      3m 30s
    6. Configuring PHP
      10m 3s
    7. Installing MySQL
      5m 46s
    8. Configuring MySQL
      7m 24s
    9. Text editor
      5m 1s
  4. 31m 25s
    1. Overview
      3m 27s
    2. Installing WampServer
      5m 46s
    3. Finding the document root
      2m 24s
    4. Configuring PHP
      8m 12s
    5. Configuring MySQL
      5m 45s
    6. Text editor
      5m 51s
  5. 19m 12s
    1. Embedding PHP code on a page
      6m 43s
    2. Outputting dynamic text
      5m 55s
    3. The operational trail
      2m 27s
    4. Inserting code comments
      4m 7s
  6. 1h 18m
    1. Variables
      7m 50s
    2. Strings
      4m 38s
    3. String functions
      8m 54s
    4. Numbers part one: Integers
      6m 27s
    5. Numbers part two: Floating points
      5m 25s
    6. Arrays
      10m 0s
    7. Associative arrays
      6m 37s
    8. Array functions
      6m 33s
    9. Booleans
      3m 50s
    10. NULL and empty
      5m 15s
    11. Type juggling and casting
      8m 27s
    12. Constants
      4m 43s
  7. 27m 37s
    1. If statements
      6m 0s
    2. Else and elseif statements
      4m 16s
    3. Logical operators
      7m 30s
    4. Switch statements
      9m 51s
  8. 42m 15s
    1. While loops
      8m 41s
    2. For loops
      5m 59s
    3. Foreach loops
      8m 16s
    4. Continue
      8m 28s
    5. Break
      4m 8s
    6. Understanding array pointers
      6m 43s
  9. 37m 25s
    1. Defining functions
      8m 25s
    2. Function arguments
      5m 32s
    3. Returning values from a function
      7m 33s
    4. Multiple return values
      4m 53s
    5. Scope and global variables
      6m 2s
    6. Setting default argument values
      5m 0s
  10. 20m 18s
    1. Common problems
      3m 47s
    2. Warnings and errors
      8m 36s
    3. Debugging and troubleshooting
      7m 55s
  11. 57m 57s
    1. Links and URLs
      5m 33s
    2. Using GET values
      5m 35s
    3. Encoding GET values
      8m 41s
    4. Encoding for HTML
      9m 26s
    5. Including and requiring files
      7m 40s
    6. Modifying headers
      6m 45s
    7. Page redirection
      6m 43s
    8. Output buffering
      7m 34s
  12. 1h 3m
    1. Building forms
      7m 28s
    2. Detecting form submissions
      5m 59s
    3. Single-page form processing
      7m 57s
    4. Validating form values
      10m 40s
    5. Problems with validation logic
      9m 54s
    6. Displaying validation errors
      7m 23s
    7. Custom validation functions
      6m 28s
    8. Single-page form with validations
      7m 25s
  13. 28m 5s
    1. Working with cookies
      2m 49s
    2. Setting cookie values
      5m 55s
    3. Reading cookie values
      6m 1s
    4. Unsetting cookie values
      4m 51s
    5. Working with sessions
      8m 29s
  14. 48m 39s
    1. MySQL introduction
      6m 43s
    2. Creating a database
      7m 41s
    3. Creating a database table
      7m 42s
    4. CRUD in MySQL
      5m 48s
    5. Populating a MySQL database
      7m 32s
    6. Relational database tables
      6m 40s
    7. Populating the relational table
      6m 33s
  15. 56m 4s
    1. Database APIs in PHP
      4m 51s
    2. Connecting to MySQL with PHP
      7m 45s
    3. Retrieving data from MySQL
      8m 47s
    4. Working with retrieved data
      6m 12s
    5. Creating records with PHP
      6m 58s
    6. Updating and deleting records with PHP
      9m 6s
    7. SQL injection
      3m 5s
    8. Escaping strings for MySQL
      6m 45s
    9. Introducing prepared statements
      2m 35s
  16. 35m 58s
    1. Blueprinting the application
      7m 19s
    2. Building the CMS database
      5m 14s
    3. Establishing your work area
      4m 38s
    4. Creating and styling the first page
      4m 22s
    5. Making page assets reusable
      6m 36s
    6. Connecting the application to the database
      7m 49s
  17. 32m 49s
    1. Adding pages to the navigation subjects
      5m 58s
    2. Refactoring the navigation
      6m 7s
    3. Selecting pages from the navigation
      6m 2s
    4. Highlighting the current page
      5m 26s
    5. Moving the navigation to a function
      9m 16s
  18. 1h 45m
    1. Finding a subject in the database
      9m 48s
    2. Refactoring the page selection
      10m 52s
    3. Creating a new subject form
      6m 55s
    4. Processing form values and adding subjects
      11m 20s
    5. Passing data in the session
      9m 16s
    6. Validating form values
      9m 40s
    7. Creating an edit subject form
      8m 30s
    8. Using single-page submission
      7m 44s
    9. Deleting a subject
      9m 44s
    10. Cleaning up
      10m 37s
    11. Assignment: Pages CRUD
      4m 30s
    12. Assignment results: Pages CRUD
      6m 10s
  19. 39m 26s
    1. The public appearance
      8m 52s
    2. Using a context for conditional code
      11m 37s
    3. Adding a default subject behavior
      6m 9s
    4. The public content area
      5m 51s
    5. Protecting page visibility
      6m 57s
  20. 1h 3m
    1. User authentication overview
      4m 3s
    2. Admin CRUD
      8m 41s
    3. Encrypting passwords
      7m 26s
    4. Salting passwords
      5m 42s
    5. Adding password encryption to CMS
      11m 54s
    6. New PHP password functions
      3m 13s
    7. Creating a login system
      11m 28s
    8. Checking for authorization
      5m 48s
    9. Creating a logout page
      5m 40s
  21. 2m 4s
    1. Next steps
      2m 4s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ .

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed PHP with MySQL Essential Training.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member ?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferences from the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

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.

Learn more, save more. Upgrade today!

Get our Annual Premium Membership at our best savings yet.

Upgrade to our Annual Premium Membership today and get even more value from your lynda.com subscription:

“In a way, I feel like you are rooting for me. Like you are really invested in my experience, and want me to get as much out of these courses as possible this is the best place to start on your journey to learning new material.”— Nadine H.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.