我正在尝试从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);
}
?>
答案 0 :(得分:0)
我曾使用一些代码在My SQL中使用hash和salt尝试使用它来存储密码,
$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