Tuesday, 18 October 2011

How to decrypt the md5 encrypted password in PHP

md5 is supposed to be a one way encryption. But we can validate the password. First create an md5 hash of the password supplied by the user, and compare that with the encrypted password in the database.

This example shows how to change the md5 encrypted password in the database 

     $username = $_POST['user']; // get the username from the  form

     $currentpassword = $_POST['password']; // get the current password from
                                                                           the form
 
     $newpassword = $_POST['newpassword']; // get the new password from the
                                                                              form
     $hash = md5($currentpassword); // encrypt the current password supplied
                                                            by the user

     $result = mysql_query("SELECT password from Users  where
     username='username' ");  // query the database for getting password for a
                                                   the user.

     $row = mysql_fetch_array($result);

     $p=$row[password]; // get the encrypted password from the database for the
                                           user
     if($p==$hash)){

           $result = mysql_query("UPDATE members set       
                           password=md5('newpassword') where username='username' ");
      } // update the new password for the user in the database in encrypted form,
            only if the encrypted current password and the password stored in the
            database are same