PHP Compare a crypted password from db with an inserted password from a form

60 views Asked by At

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!

1

There are 1 answers

1
Just Lucky Really On BEST ANSWER

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.