简体   繁体   English

如何检查数据库中的密码是否匹配?

[英]How do i check for a match for password in database?

Today I found a php class called CryptoLib it helps in hashing password, but now I'm confused how will I match it with my database password. 今天,我发现了一个名为CryptoLib的php类,它有助于哈希密码,但是现在我很困惑如何将其与数据库密码匹配。

Here is how the script is used, this generate a different hash every time I reload the page 这是脚本的使用方式,每次我重新加载页面时,都会生成不同的哈希

$string = $_POST['password'];
echo $hash = CryptoLib::hash($string);

This above line check if hash is a matched or not 上面的这一行检查哈希是否匹配

$isHashCorrect = CryptoLib::validateHash($hash, $string);
echo ($isHashCorrect ? "TRUE" : "FALSE");

This is my query 这是我的查询

mysqli_query($connec, "SELECT * FROM users WHERE email='$email' AND password='$password'");

Now can somebody tell me how can I match the password? 现在有人可以告诉我如何匹配密码吗?

For more info visit https://cryptolib.ju.je/ 有关更多信息,请访问https://cryptolib.ju.je/

You basically need to compare the supplied password with the hash that is in the database through a SELECT query and iterate over the given row, just as you would for PHP's password_verify() function. 基本上,您需要通过SELECT查询将提供的密码与数据库中的哈希进行比较,并遍历给定的行,就像使用PHP的password_verify()函数一样。

An example of this and where you bind the result to the comparison: 一个示例以及将结果绑定到比较的地方:

$username = "email@example.com";
$password = "pass";

    if ($stmt = $con->prepare("SELECT `password` FROM `table` WHERE email = ? ")) {

        $stmt -> bind_param("s", $username);

        /* Execute it */
        $stmt -> execute();

        /* Bind results */
        $stmt -> bind_result($result);

        /* Fetch the value */
        $stmt -> fetch();

        /* Close statement */
        $stmt -> close();
    }

$isHashCorrect = CryptoLib::validateHash($result, $password);
echo ($isHashCorrect ? "TRUE" : "FALSE");

While using a prepared statement . 在使用准备好的语句时 Something you should use in order to help protect against a possible SQL injection which you are presently open to. 您应该使用某种东西来帮助防止可能的SQL注入 ,您目前对此开放。

Also noting from my comments: 还注意到我的评论:

That library returns a 256 length string. 该库返回一个256个长度的字符串。 Make sure your password column in your database isn't 255 but 256+, because that will fail on you silently . 确保数据库中的密码列不是255,而是256+,因为这将对您无声地失败。

You might even like to use PHP's password_hash() function instead, yet that choice is entirely yours. 您甚至可能想改用PHP的password_hash()函数,但这种选择完全是您的选择。


Foonotes: Foonotes:

This line require_once('cryptolib.php'); 这行require_once('cryptolib.php'); from their demo file might throw you an error if you're on a *NIX system. 如果您使用的是* NIX系统,则从其演示文件中获取数据可能会导致您出错。 Those are case-sensitive if you're on that (instead of Windows). 如果您使用的是Windows(而不是Windows),则它们区分大小写。 Their file is named CryptoLib.php and is not the same as cryptolib.php on certain platforms. 他们的文件名为CryptoLib.php ,在某些平台上与cryptolib.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM