Question

I'm currently working on a site where the client stores the password in a MySQL database using the 'password' function.

The new database will be storing encrypted passwords using a combination of MD5 and Salt.

So I copied the existing user's over to our database with the encrypted passwords but when the password function is run to check the login it always returns an incorrect password. When I check the results of the password function on the correct password it produces a different result to what is stored.

Is there some extra work I need to do to get the encryption to match and produce the same result? do I have to access the passwords directly fro the clients web site? (as i have copied there user table to our local DB)

Was it helpful?

Solution

In order to get the same result from encryption, you have to use the same mechanism to encrypt before you compare hashes.

If you have created the original password hashes with the password function, the hash will look like this (for the current version of the PASSWORD function

    *196BDEDE2AE4F84CA44C47D54D78478C7E2BD7B7

or like this if created with the OLD_PASSWORD function (before mysql 4.1 ... )

    29bad1457ee5e49e

The straight way to deal with this is to have your authentication query look something like this

    select count(*) as authfield from your_auth_table 
    where username = 'typed-in-username'
    and
    (
         password = password('typed-in-password')
         or password = old_password('typed-in-password')
    )

If username and password match, this will yield authfield = 1

If you want to do the encryption yourself in PHP, the correspondent to the mysql PASSWORD algorythm goes like this:

  $passwordnew = '*'. strtoupper(sha1(hextostr(sha1('pass'))));


  function hextostr($hex)
  {
      $str='';
      for ($i=0; $i < strlen($hex)-1; $i+=2)
      {
            $str .= chr(hexdec($hex[$i].$hex[$i+1]));
      }
      return $str;
  }  

For the old_password function you can use

 $passwordold = old_password('pass');

 function old_password($password) {
   if ($password == '')
      return '';
   $nr = 1345345333;
   $add = 7;
   $nr2 = 0x12345671;
   foreach(str_split($password) as $c) {
      if ($c == ' ' or $c == "\t")
         continue;
      $tmp = ord($c);
      $nr ^= ((($nr & 63) + $add) * $tmp) + ($nr << 8);
      $nr2 += ($nr2 << 8) ^ $nr;
      $add += $tmp;
   }

   if ($nr2 > PHP_INT_MAX)
      $nr2 += PHP_INT_MAX + 1;

   return sprintf("%x%x", $nr, $nr2);
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top