PHP 将来自数据库的加密密码与来自表单的插入密码进行比较

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

我有一个带加密密码的数据库。当用户登录时,我这样做:

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

它有效,但我想知道这是否正确,或者是否有更安全的方法!

不要使用 MD5。有很多在线文档可以解释这是多么不安全。例如:

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

我建议使用 crypt() 函数。

阅读此处:http://php.net/crypt

一个很好用的是 CRYPT_BLOWFISH

这是我不久前发现并使用的一个函数。不幸的是,我不记得在哪里找到它,所以我无法引用作者。

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,'y$' . $rounds . '$' . $salt);

        return $hashstring;
    }

要创建加密密码,您可以像这样使用它:

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

然后比较,你会使用:

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

注意:如果您使用的是PHP5.3.7之前的版本,salt前缀必须是a$

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