douji5523 2014-03-28 16:48
浏览 65
已采纳

登录时比较哈希时出错

i'm creating a simple login system, i has the passwords using sha256 and store a salt using a random number in the database. However when i try to log in, when it goes to compare the hashes it fails. Can anyone see why?

   <?php
session_start();

$username = $_POST['username'];
$password = $_POST['password'];

$mysql_db_hostname = "localhost";
$mysql_db_user = "root";
$mysql_db_database = "login";

$con = mysql_connect($mysql_db_hostname, $mysql_db_user) or die("Could not connect database");
mysql_select_db($mysql_db_database, $con) or die("Could not select database");

$query = "SELECT password, salt FROM registered_users WHERE username='$username'";
$result = mysql_query($query);
if(mysql_num_rows($result) < 1) //no such user exists
{

            echo 'false';
            header('Location: index.php');
}
$userData = mysql_fetch_array($result, MYSQL_ASSOC);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $password) );
if($hash != $userData['password']) //incorrect password
{   

            echo 'false';
            header('Location: index.php');

}
else
{
    echo 'true';
     $_SESSION['username']=$row['username'];    

}
session_write_close();

Heres how i hash my pass

// hash the password using sha256 a string of 64 characters
$hash = hash('sha256', $password);
// create the salt, random string of characters appened to hash
function createSalt()
{
    $string = md5(uniqid(rand(), true));
    return substr($string, 0, 3);
}
$salt = createSalt();
$hash = hash('sha256', $salt . $hash);

Heres how i insert my data

mysql_query("INSERT INTO registered_users(username, name, email, password,salt)VALUES('$username', '$name', '$email', '$hash', '$salt')");
header("location: index.php?remarks-success");
mysql_close($con);
?>
  • 写回答

1条回答 默认 最新

  • douxie1692 2014-03-28 16:53
    关注

    Make sure you are storing the password in the database the same way you are checking it here.

    So to put it in you should create the hash by first hashing the password, then rehashing it with a salt. If they don't match, then there is your problem.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图