[英]PHP & MYSQL: using bcrypt hash and verifying password with database
[英]Password verifying against database using bcrypt
我试图验证密码与数据库中的密码,但它不起作用。 请查看我的代码,让我知道什么是错的。
用于将用户名和密码存储到数据库的代码。
<?php
echo "enter the username \n";
$username = trim(fgets(STDIN));
echo "enter the password\n";
$password = trim(fgets(STDIN));
//connecting to database
$con=mysqli_connect("localhost","sqldata","sqldata","accounts");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$salt = substr(sha1(mt_rand()),0,22);
$hashedPassword= crypt($password , '$2y$10$' . $salt);
echo $hashedPassword;
mysqli_query($con,"INSERT INTO login (username, password)
VALUES ('$username', '$hashedPassword')");
mysqli_close($con)
?>
验证密码的代码如下
<?php
echo "enter the username \n";
$username = trim(fgets(STDIN));
echo "enter the password\n";
$password = trim(fgets(STDIN));
//connecting to database
$db = mysql_connect("localhost","sqldata","sqldata") or die(mysql_error());
//selecting our database
$db_select = mysql_select_db("accounts", $db) or die(mysql_error());
$result= mysql_query("select * from login where username = '$username' ");
if ( !$result ) exit( "$userName wasn't found in the database!" );
$row = mysql_fetch_array( $result );
$storedPassword = $row['password'];
$salt = substr(sha1(mt_rand()),0,22);
$hashedPassword= crypt($password , '$2y$10$' . $salt);
if (crypt($hashedPassword) == $storedPassword)
{
echo "ok";
}
else
{
echo "error";
}
?>
将密码保存到正在使用的数据库时:
$hashedPassword= crypt($password , '$2y$10$' . $salt);
但是当你检索密码并检查它时我发现了一些错误:
$storedPassword = $row['password'];
$salt = substr(sha1(mt_rand()),0,22);
$hashedPassword= crypt($password , '$2y$10$' . $salt);
if (crypt($hashedPassword) == $storedPassword){/*...*/}
1,不应该:
$hashedPassword= crypt($password, '$2y$10$' . $salt);
是
$hashedPassword= crypt($storedPassword, '$2y$10$' . $salt);
2,看来你正在使用crypt
两次:
$hashedPassword= crypt($password , '$2y$10$' . $salt);
if (crypt($hashedPassword) == $storedPassword)
所以不应该只是:
$hashedPassword= crypt($storedPassword, '$2y$10$' . $salt);
if ($hashedPassword == $storedPassword){/*...*/}
这比你想象的要简单。 crypt格式有点聪明:它包含salt作为加密密码的开头,格式为(方法)(salt)(哈希)。
使用crypt()时,它只查看(方法)(盐)并使用它们返回(方法)(盐)(哈希),因此要验证密码,您需要做的就是将加密的密码作为盐传递并查看结果是否匹配。 也就是说,
crypt($testPassword, $hashedPassword) === $hashedPassword
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.