如何在PHP中解密密码哈希

如何在PHP中解密密码哈希

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

问题描述

我需要解密密码。密码用password_hash函数加密。

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

现在,我们假设$ crypted存储在数据库中(有一个users表,用户名,密码等),我需要登录:我必须看看用户输入的密码是否与存储在数据库中的加密密码相符。



是sql代码...

  $ sql_script ='select * from USERS where username ='。$ username。'和password ='。$ inputpassword。''; 

...但$ inputpassword没有被隐藏,所以它不等于密码中存储的内容表用户的字段...



所以,在使用password_hash之后有一个解密功能吗?还是应该更改我的加密方式?或者还有什么?

解决方案

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

 <?php 
//查看password_hash()示例,看看这是从哪来的。
$ hash ='$ 2y $ 07 $ BCryptRequires22Chrcte / VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';

if(password_verify('rasmuslerdorf',$ hash)){
echo'密码有效!
} else {
echo'无效的密码'。
}
?>

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

  $ sql_script ='select * from USERS where username ='。$ username。''; 

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

编辑:以这种方式构造查询是非常危险的。如果您没有正确地转义输入,代码将容易受到SQL注入攻击。有关如何防止SQL注入,请参阅的答案。


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

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

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 crypted password stored in the database.

This is the sql code...

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

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

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

解决方案

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.';
}
?>

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

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

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

Edit: Constructing the query this way is very dangerous. If you don't escape the input properly, the code will be vulnerable to SQL injection attacks. See this SO answer on how to prevent SQL injection.

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

08-20 19:07