我使用以下代码将密码存储到 mysql
if (!$errors) {
// include the connection file
require_once('connection.inc.php');
$conn = dbConnect('write');
// create a salt using the current timestamp
$salt = time();
// encrypt the password and salt
$pwd = sha1($password, $salt);
echo $pwd;
// prepare SQL statement
$sql = 'INSERT INTO users (username, salt, pwd)
VALUES (?, ?, ?)';
$stmt = $conn->stmt_init();
$stmt = $conn->prepare($sql);
// bind parameters and insert the details into the database
$stmt->bind_param('sis', $username, $salt, $pwd);
$stmt->execute();
if ($stmt->affected_rows == 1) {
$success = "$username has been registered. You may now log in.";
} elseif ($stmt->errno == 1062) {
$errors[] = "$username is already in use. Please choose another username.";
} else {
$errors[] = 'Sorry, there was a problem with the database.';
}
}
密码字段 pwd 定义为 CHAR 40。当我检查它时,我发现它包含以下内容:
ƒ7Ž{9‰ù|EòsŒs”ºþ
无论我输入什么密码。自然,当我尝试使用以下代码登录时,这与密码无法比较:
require_once('connection.inc.php');
$conn = dbConnect('read');
// get the username's details from the database
$sql = 'SELECT salt, pwd FROM users WHERE username = ?';
// initialize and prepare statement
$stmt = $conn->stmt_init();
$stmt->prepare($sql);
// bind the input parameter
$stmt->bind_param('s', $username);
// bind the result, using a new variable for the password
$stmt->bind_result($salt, $storedPwd);
$stmt->execute();
$stmt->fetch();
// encrypt the submitted password with the salt
// and compare with stored password
if (sha1($password . $salt) == $storedPwd) {
$_SESSION['authenticated'] = 'Jethro Tull';
// get the time the session started
$_SESSION['start'] = time();
session_regenerate_id();
header("Location: $redirect");
exit;
} else {
// if no match, prepare error message
echo " pwd " . $password;
echo " salt " . $salt;
echo " sha1 " . sha1($password . $salt);
echo " St. pwd " . $storedPwd;
$error = 'Invalid username or password';
}
有谁知道为什么会这样?