php - php 中的 sha1 未正确存储在 mysql 中

标签 php mysql sha1

我使用以下代码将密码存储到 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/

相关文章:

php - .htaccess with -Indexes 在给定目录时陷入无限重定向循环

php - 在单个表单中插入到 php 中的多个表中

c++ - MySQL PreparedStatement 注意事项

node.js - 如何在 Node.js 中实现 "Base64 encoded SHA-1 hash of a string"

c# - 如何在 PHP 中解密 C# 中使用 3DES 加密的字符串?

php - 如何使用 Apache SOLR 和 PHP 代码突出显示搜索结果

c# - 不同的 WCF 绑定(bind),它们的区别以及与其他平台的兼容性

mysql - 在 mySQL 中创建 View 查询时数据丢失

将 char* 转换为 unsigned char*

go - UUID 的 Sha1 十六进制 - 用作访问 token