我使用以下代码将密码存储到 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';
}
有谁知道为什么会这样吗?
最佳答案
不确定这是否是您唯一的问题,但是
$pwd = sha1($password, $salt);
不是您使用sha1
函数的方式。 http://php.net/manual/en/function.sha1.php
time()
将始终评估为 TRUE
,因此您将原始二进制格式插入到字符密码字段中。导致您所看到的问题。
您可能想做的是
$pwd = sha1($password . $salt);
^
关于php - php 中的 sha1 未正确存储在 mysql 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12941923/