0

I've a db with crypted password. When a user logs in, i make this:

$result = mysqli_fetch_assoc(mysqli_query($conn,$query));
$cryptedPass = $result['password'];
$pass = $_POST['password'];
if(strcmp($cryptedPass,md5($pass))==0)
   echo "yeah!";

It works, but I would like to know if this the right manner, or if there is something of safer!

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
ProtoTyPus
  • 1,272
  • 3
  • 19
  • 40

1 Answers1

1

Don't use MD5. There are plenty of online documents that explain how insecure this is. For example:

https://en.wikipedia.org/wiki/MD5

I would recommend using the crypt() function.

Read here: http://php.net/crypt

A good one to use would be CRYPT_BLOWFISH

Here's a function I found a while back, that I use. Unfortunately I can't remember where I found it, so I can't reference the author.

function blowfishEncrypt($string,$rounds) {
        $salt = "";
        $saltCharacters = array_merge(range('A','Z'),range('a','z'),range(0,9));
        for ($i=0;$i<22;$i++) {
            $salt .= $saltCharacters[array_rand($saltCharacters)];
        }
        $hashstring = crypt($string,'$2y$' . $rounds . '$' . $salt);

        return $hashstring;
    }

To create the encrypted password, you would use it like so:

$cryptedPass=blowfishEncrypt($clearPass,'07');

Then to compare, you would use:

if($cryptedPass==crypt($pass,$cryptedPass)) {
    echo 'Yeah!';
}

Note: If you are using a version of PHP before 5.3.7, the salt prefix must be $2a$.

PHP 5.3.7 introduced the new prefix $2y$ to fix a security weakness in the Blowfish implementation.

Just Lucky Really
  • 1,341
  • 1
  • 15
  • 38
  • Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackoverflow.com/rooms/80943/discussion-on-answer-by-stretch-php-compare-a-crypted-password-from-db-with-an-i). – Martijn Pieters Jun 18 '15 at 21:37