如何使用PHP的password_hash哈希和验证密码 [英] How to use PHP's password_hash to hash and verify passwords

查看:373
本文介绍了如何使用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存储密码.不要将它们分离为数据库和文件.

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

假设我们输入以下内容:

Let's say we have the following input:

$password = $_POST['password'];

我不仅仅为了理解概念而验证输入.

I don't validate the input just for the sake of understanding the concept.

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

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).

现在,您将此hashed_pa​​ssword存储在数据库中,确保您的password列足够大以容纳哈希值(至少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天全站免登陆