View Single Post
Old 02-03-2009, 09:35 PM   #4 (permalink)
Dog Cow
The Visitor
 
Join Date: Feb 2009
Posts: 2
Thanks: 0
Dog Cow is on a distinguished road
Default

Quote:
Originally Posted by code_junkie View Post
I am having trouble understanding the md5() function. Can anyone explain it a little and explain how to implement it into my login script?
Basically, making an MD5 hash is like making a footprint. It's not actually your foot, but only your foot will match!

In the same case, when a user registers, you make an MD5 hash of his password like this:

Code:
if (isset($_POST['submit']))
{
  // user has submit the registration form

  $password = $_POST['password']; // user's plaintext password as submitted by the form

  // In this example, we will assume the user entered
  // greendog32
  // as his password.

  // Now we make an MD5 hash of this.
  $md5_hash = md5($password);

  // $md5_hash currently looks like this:
  // 742898c83a580b611249ecc2f6cc7a2d

  // More code here would insert this hash into a database
  // The original, plaintext password that the user entered is discarded!

}
Now the thing you have to understand is that with MD5, every possible combination of characters hashes to a completely unique, 32 alphanumeric string. In theory, this is the ideal case, in practice, no.

In example:
the hash of the single letter a is : 0cc175b9c0f1b6a831c399e269772661
and the hash of a similar string, aa is: 4124bc0a9335c27f086f24ba207a4912

Quite different, even though the inputs are similar.

Now, here is part 2! We have the MD5 hash of the user's password stored, which is not the actual password. In theory, there should be only one phrase in the entire world which equals the hash, and that is greendog32.

So, here is what the login script would look like:

Code:
if(isset($_POST['submit']))
{
  // user has submit the login form

  // Here is the plaintext password which the user has entered
  $password = $_POST['password'];

  // Some code here will select the MD5 hash from the database
  $hash_from_database = '742898c83a580b611249ecc2f6cc7a2d';

  // Now what we do here is md5() the password which the user just submitted
  // and see if it equals $hash_from_database

  $hash_from_user = md5($password);

  // Now compare!
  if ($hash_from_user == $hash_from_database)
  {
     echo('You have entered the password correctly! The MD5 hashes matched!');
  }
  else
  {
      echo('You have entered a password other than greendog32. 
      Since the hashes did not match, the password you entered was wrong!');
  }

}
Dog Cow is offline  
Reply With Quote
The Following 2 Users Say Thank You to Dog Cow For This Useful Post:
code_junkie (02-04-2009), Wildhoney (02-03-2009)