php如何比较数据库中的密码,php – 如何从数据库和auth用户收回盐渍密码?

开发人员通常很难验证登录密码,因为他们不确定如何处理存储的密码哈希.他们知道密码应该使用适当的函数(如 password_hash())进行哈希处理,并将它们存储在varchar(255)字段中:

// Hash a new password for storing in the database.

// The function automatically generates a cryptographically safe salt.

$hashToStoreInDb = password_hash($password, PASSWORD_DEFAULT);

在登录表单中,我们无法直接使用SQL验证密码,也无法搜索密码,因为存储的哈希值已被加密.相反,我们……

>必须从数据库中读取密码哈希,按用户ID搜索

>然后可以使用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 db, searching by username

$sql = 'SELECT password FROM users WHERE username = ?';

$stmt = $mysqli->prepare($sql);

$stmt->bind_param('s', $_POST['username']); // 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);

}

请注意,该示例使用预准备语句来避免SQL注入,在这种情况下不需要转义.从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 db, searching by username

$sql = 'SELECT password FROM users WHERE username = ?';

$stmt = $pdo->prepare($sql);

$stmt->bindValue(1, $_POST['username'], 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);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值