如何在 PHP 中解密密码哈希? [英] How can I decrypt a password hash in PHP?

查看:62
本文介绍了如何在 PHP 中解密密码哈希?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要解密密码.密码使用password_hash函数加密.

I need to decrypt a password. The password is encrypted with password_hash function.

$password = 'examplepassword';
$crypted = password_hash($password, PASSWORD_DEFAULT);

现在,让我们假设 $crypted 存储在数据库中(有一个用户"表,包含用户名、密码等),我需要登录:我必须看看用户输入的密码与数据库中存储的加密密码一致.

Now, let's assume that $crypted is stored in a database (there's a "users" table, with usernames, passwords, etc) and I need to do a login: I have to see if the password entered by the user matches the encrypted password stored in the database.

这是sql代码...

$sql_script = 'select * from USERS where username="'.$username.'" and password="'.$inputpassword.'"';

...但是$inputpassword没有加密,所以不等于表users的password字段中存储的内容...

...but $inputpassword is not encrypted, so it's not equal to what is stored in the password field of the table users...

那么,有没有使用password_hash后解密的功能?或者我应该改变我的加密方法?或者还有什么?

So, there's a function to decrypt after the use of password_hash? Or should I change my encrypt method? Or what else?

推荐答案

Bcrypt 是一种单向散列算法,您无法解密散列.使用 password_verify 检查密码是否与存储的哈希匹配:

Bcrypt is a one-way hashing algorithm, you can't decrypt hashes. Use password_verify to check whether a password matches the stored hash:

<?php
// See the password_hash() example to see where this came from.
$hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';

if (password_verify('rasmuslerdorf', $hash)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}

在您的情况下,仅使用用户名运行 SQL 查询:

In your case, run the SQL query using only the username:

$sql_script = 'SELECT * FROM USERS WHERE username=?';

并使用与上述示例类似的代码在 PHP 中进行密码验证.

And do the password validation in PHP using a code that is similar to the example above.

您构建查询的方式非常危险.如果您没有正确地参数化输入,代码将容易受到 SQL 注入攻击.请参阅此堆栈溢出答案,了解如何防止 SQL 注入.

The way you are constructing the query is very dangerous. If you don't parameterize the input properly, the code will be vulnerable to SQL injection attacks. See this Stack Overflow answer on how to prevent SQL injection.

这篇关于如何在 PHP 中解密密码哈希?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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