gpt4 book ai didi

php - 加盐和散列在 php 登录中不起作用

转载 作者:行者123 更新时间:2023-11-30 21:54:54 26 4
gpt4 key购买 nike

我正在尝试从 O'Reilly(Robin Nixon)那里学习 PHP,但那本书中编写的代码无法正常工作。我已经使用此代码将值添加到数据库中

    $query = "CREATE TABLE users (
forename VARCHAR(32) NOT NULL,
surname VARCHAR(32) NOT NULL,
username VARCHAR(32) NOT NULL UNIQUE,
password VARCHAR(32) NOT NULL)";
$result = $conn->query($query);
if (!$result) die($conn->error);*/

$salt1 = "qm&h*"; $salt2 = "pg!@";

$forename = 'Bill';
$surname = 'Smith';
$username = 'bsmith';
$password = 'mysecret';
$token = hash("ripemd128", "$salt1$password$salt2");

add_user($conn,$forename,$surname,$username,$token);

$forename = 'Pauline';
$surname = 'Jones';
$username = 'pjones';
$password = 'acrobat';
$token = hash('ripemd128', '$salt1$password$salt2');

add_user($conn,$forename,$surname,$username,$token);

function add_user($conn,$fn,$sn,$un,$pw) {
$query = "INSERT INTO users VALUES('$fn','$sn','$un','$pw')";
$result = $conn->query($query);
if (!$result) die($conn->error);
}

然后当我尝试登录时,出现错误。为了更好地理解,我自定义了错误语句,它给了我 error1。我还尝试在不使用散列和加盐的情况下将密码存储在数据库中,之后当我尝试不使用散列和加盐登录时,它工作得很好,这证明问题出在散列或加盐或两者兼而有之。我正在根据书中使用以下代码。

    if (isset($_SERVER['PHP_AUTH_USER']) &&
isset($_SERVER['PHP_AUTH_PW']))
{
$un_temp = mysql_entities_fix_string($conn, $_SERVER['PHP_AUTH_USER']);
$pw_temp = mysql_entities_fix_string($conn, $_SERVER['PHP_AUTH_PW']);

$query = "SELECT * FROM users WHERE username='$un_temp'";
$result = $conn->query($query);
if (!$result) {
die($conn->error);
} elseif($result->num_rows) {
$row = $result->fetch_array(MYSQLI_NUM);
$result->close();
$salt1 = "qm&h*"; $salt2 = "pg!@";
$token = hash("ripemd128", "$salt1$pw_temp$salt2");

if ($token == $row[3]) {
echo "$row[0] $row[1] : Hi $row[0], you are now logged in as '$row[2]'";
} else {
die("error1 - Invalid username/password combination");
}
} else {
die("error2 - Invalid 2 username/password combination");
}
} else {
header('WWW-Authenticate: Basic realm="Restricted Section"');
header('HTTP/1.0 401 Unauthorized');
die("Please enter your username and password");
}
$conn->close();

function mysql_entities_fix_string($conn, $string) {
return htmlentities(mysql_fix_string($conn, $string));
}
function mysql_fix_string($conn, $string) {
if (get_magic_quotes_gpc()) $string = stripslashes($string);
return $conn->real_escape_string($string);
}
?>

最佳答案

我曾使用一些代码通过散列和盐尝试使用它在 My SQL 中存储密码,

$salt="pg!@";
$password="abcd";(for example)
$password_salt = $password.$salt;
$password_hash = hash('sha256', $password_salt);
u can use this password hash in your query for storing password.

Hope it helps

关于php - 加盐和散列在 php 登录中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45608297/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com