如何使用 PHP 的 password_hash 对密码进行散列和验证 [英] How to use PHP's password_hash to hash and verify passwords

查看:31
本文介绍了如何使用 PHP 的 password_hash 对密码进行散列和验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我一直试图在我在互联网上偶然发现的登录脚本上实现我自己的安全性.在努力学习如何制作自己的脚本来为每个用户生成盐后,我偶然发现了 password_hash.

Recently I have been trying to implement my own security on a log in script I stumbled upon on the internet. After struggling of trying to learn how to make my own script to generate a salt for each user, I stumbled upon password_hash.

据我所知(基于对本页的阅读),当你使用 password_hash 时,salt 已经在行中生成了.这是真的?

From what I understand (based off of the reading on this page), salt is already generated in the row when you use password_hash. Is this true?

我的另一个问题是,有 2 种盐不是很聪明吗?一个直接在文件中,一个在数据库中?那样的话,如果有人破坏了你在数据库中的盐,你仍然直接在文件中拥有盐吗?我在这里读到,储存盐从来都不是一个聪明的主意,但它总是让我困惑人们的意思.

Another question I had was, wouldn't it be smart to have 2 salts? One directly in the file and one in the DB? That way, if someone compromises your salt in the DB, you still have the one directly in the file? I read on here that storing salts is never a smart idea, but it always confused me what people meant by that.

推荐答案

使用 password_hash 是存储密码的推荐方式.不要将它们分开为 DB 和文件.

Using password_hash is the recommended way to store passwords. Don't separate them to DB and files.

假设我们有以下输入:

$password = $_POST['password'];

您首先通过执行以下操作对密码进行哈希处理:

You first hash the password by doing this:

$hashed_password = password_hash($password, PASSWORD_DEFAULT);

然后看输出:

var_dump($hashed_password);

正如你所见,它是经过哈希处理的.(我假设您已经完成了这些步骤).

As you can see it's hashed. (I assume you did those steps).

现在您将此散列密码存储在您的数据库中,确保您的密码列足够大以保存散列值(至少 60 个字符或更长).当用户要求登录时,您可以在数据库中使用此哈希值检查密码输入,方法如下:

Now you store this hashed password in your database, ensuring your password column is large enough to hold the hashed value (at least 60 characters or longer). When a user asks to log them in, you check the password input with this hash value in the database, by doing this:

// Query the database for username and password
// ...

if(password_verify($password, $hashed_password)) {
    // If the password inputs matched the hashed password in the database
    // Do something, you know... log them in.
} 

// Else, Redirect them back to the login page.

官方参考

这篇关于如何使用 PHP 的 password_hash 对密码进行散列和验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆