使用PHP比较MySql密码()

使用PHP比较MySql密码(),php,mysql,passwords,Php,Mysql,Passwords,我发现这篇文章很有帮助,但我在应用上面提供的解决方案解决我的问题时遇到了困难 使用password()将密码存储在Mysql中。我想调整此脚本,将输入的密码与存储在数据库中的密码进行比较,而不是使用“crypt()”函数 public function authenticate($user,$pass) { $mysqli = new mysqli(DBHOST,DBUSER,DBPASS,DB); if ($mysqli->connect_errn

我发现这篇文章很有帮助,但我在应用上面提供的解决方案解决我的问题时遇到了困难

使用
password()
将密码存储在Mysql中。我想调整此脚本,将输入的密码与存储在数据库中的密码进行比较,而不是使用“crypt()”函数

    public function authenticate($user,$pass) {
        $mysqli = new mysqli(DBHOST,DBUSER,DBPASS,DB);
        if ($mysqli->connect_errno) {
        error_log("Cannot connect to MySQL: " . $mysqli->connect_error);
        return false;
        }
        $safeUser = $mysqli->real_escape_string($user);
        $incomingPassword = $mysqli->real_escape_string($pass);
        $query = "SELECT * from users WHERE username ='{$safeUser}'";
        if (!$result = $mysqli->query($query)) {
            error_log("Cannot retrieve account for {$user}");
            return false;
        }

        // Will be only one row, so no while() loop needed
        $row = $result->fetch_assoc();
        $dbPassword = $row['password'];
        if (crypt($incomingPassword,$dbPassword) != $dbPassword) {
        error_log("Passwords for {$user} don't match");
        return false;
        }
        $this->id = $row['id'];
        $this->firstName = $row['first_name'];
        $this->lastName = $row['last_name'];            
        $this->username = $row['username'];
        $this->email = $row['email'];
        $this->dateJoin = $row['dateJoin'];
        $this->school = $row['school'];
        $this->level = $row['level'];
        $this->isLoggedIn = true;
        $this->_setSession();
        return true;
    } //end function authenticate
有没有一个简单的方法来调整这个脚本?我要补充一下吗

AND `password` = PASSWORD('{$incomingPassword}')

对我的问题?这似乎有点笨拙。

你真的确定使用MySql
Password()
函数散列的密码,因为这个函数是?不可能在SQL查询中安全存储密码和直接验证密码

您真的应该使用像BCrypt这样的慢散列函数,并且盐析是必需的。这意味着,您需要一个两步过程,首先使用SQL查询按用户名获取存储的密码哈希,然后从哈希中提取salt并进行验证

使用PHP散列密码的推荐方法是新函数:


如果您对有关此主题的更深入信息感兴趣,可以查看我的关于安全存储密码的说明。

您需要使用准备好的/参数化的查询。否则,您将很容易受到SQL注入攻击,当人们使用撇号时,您的代码会随机失败。
real\u escape\u string
完全足以抵御SQL注入。您应该看到“注意事项”在密码函数手册中:我建议使用
crypt
函数并将结果哈希存储在数据库中。您也可以使用satting技术和其他更好的方法。是的,您可以使用where子句中的'and
password
=password(“{$incomingPassword}')。或者您可以使用内置md5函数,例如“where
password
=md5(“{$incomingPassword}”)。不建议将md5用作密码存储方法@保罗·曼宁:这被认为太快了。谢谢你的回复和我水平的优秀教程!
// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT);

// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($password, $existingHashFromDb);