首页 > 数据库 > mysql教程 > 如何使用数据库中存储的加盐密码安全地对用户进行身份验证?

如何使用数据库中存储的加盐密码安全地对用户进行身份验证?

Linda Hamilton
发布: 2024-12-05 03:39:09
原创
890 人浏览过

How to Safely Authenticate Users with Salted Passwords Stored in a Database?

如何从数据库中撤回加盐密码并对用户进行身份验证

使用存储在数据库中的加盐密码实现会员网站时,确保正确的身份验证变得至关重要。但是,尝试检查用户是否存在时可能会出现错误。

问题

下面的代码片段演示了验证成员是否存在的错误方法:

$name = mysqli_real_escape_string($connect, $_POST['name']);
$password = mysqli_real_escape_string($connect, $_POST['password']);
$saltQuery = "SELECT salt FROM users WHERE name = '$name';";
$result = mysqli_query($connect, $saltQuery);
if ($result === false){
    die(mysqli_error());
}
$row = mysqli_fetch_assoc($result);
$salt = $row['salt'];
登录后复制

此代码尝试从数据库中检索盐,但如果查询返回则失败false。

解决方案

为了准确验证用户的登录凭据,我们需要检索存储的密码哈希并将其与用户输入的密码进行比较。此过程涉及使用 password_hash()password_verify() 函数。

MySQLi 的示例代码

/**
 * mysqli example for a login with a stored password-hash
 */
$mysqli = new mysqli($dbHost, $dbUser, $dbPassword, $dbName);
$mysqli->set_charset('utf8');

// Find the stored password hash in the database, searching by username
$sql = 'SELECT password FROM users WHERE name = ?';
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('s', $_POST['name']); // it is safe to pass the user input unescaped
$stmt->execute();

// If this user exists, fetch the password-hash and check it
$isPasswordCorrect = false;
$stmt->bind_result($hashFromDb);
if ($stmt->fetch() === true) {
  // Check whether the entered password matches the stored hash.
  // The salt and the cost factor will be extracted from $hashFromDb.
  $isPasswordCorrect = password_verify($_POST['password'], $hashFromDb);
}
登录后复制

示例代码PDO

/**
 * pdo example for a login with a stored password-hash
 */
$dsn = "mysql:host=$dbHost;dbname=$dbName;charset=utf8";
$pdo = new PDO($dsn, $dbUser, $dbPassword);

// Find the stored password hash in the database, searching by username
$sql = 'SELECT password FROM users WHERE name = ?';
$stmt = $pdo->prepare($sql);
$stmt->bindValue(1, $_POST['name'], PDO::PARAM_STR); // it is safe to pass the user input unescaped
$stmt->execute();

// If this user exists, fetch the password hash and check it
$isPasswordCorrect = false;
if (($row = $stmt->fetch(PDO::FETCH_ASSOC)) !== false) {
  $hashFromDb = $row['password'];

  // Check whether the entered password matches the stored hash.
  // The salt and the cost factor will be extracted from $hashFromDb.
  $isPasswordCorrect = password_verify($_POST['password'], $hashFromDb);
}
登录后复制

以上是如何使用数据库中存储的加盐密码安全地对用户进行身份验证?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板