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 SQL Server下载
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求