在 PHP/mysql 中使用 SHA1 密码加密的问题

Issues with using SHA1 password encryption in PHP/mysql

我有一个简单的用户登录脚本。我在 mySQL 数据库 table 中将密码加密为 SHA1(使用字符集 utf8_unicode_ci)。

当我 运行 "$q" 在数据库中的值 returns 结果没问题。但是即使输入正确的凭据后通过脚本,我也无法登录。此外,如果我在两个地方(脚本和数据库)删除加密,它工作正常。如果我改用 MD5,也会出现同样的问题。

我不确定我错过了什么。我试图回显 SHA1 输出,结果发现它与数据库中可见的加密密码不同。我也检查了我的输入中是否有任何额外的空格。请帮我理解哪里出了问题。需要帮助请叫我。提前致谢!

connection.php 保存数据库的登录凭据和以下行:

$dbc = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());

登录页面如下:"login.php"

<?php 

#Start the session:
session_start();
include('../setup/connection.php'); 

if($_POST) {
    $q = "select * from users where email = '$_POST[email]' and password = SHA1('$_POST[password]');";
    $r = mysqli_query($dbc, $q);

    if (mysqli_num_rows($r) == 1) {
        $_SESSION['username'] = $_POST['email'];
        header('Location: index.php');
    }
    else {$msg="Username/Password incorrect. Please try again!";}
}
?>

<!DOCTYPE html>
<html lang="en">
  <head>

    <meta charset="utf-8">
    <title>Admin Login</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <?php include('config/css.php'); ?>
    <?php include('config/favicon.php'); ?>
    <?php include('config/js.php'); ?>
    <!--[if lt IE 9]>
    <script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/r29/html5.min.js"></script>
    <![endif]-->

  </head>

  <body>

    <!--NAVIGATION BAR-->
    <?php //include(D_TEMPLATE.'/navigation.php'); ?>
    <div class="container">


      <div class="col-lg-4 col-lg-offset-4">
        <div class="panel panel-info">
          <div class="panel-heading">
            <h1 class="lato fs20"><strong>Login</strong></h1>
          </div>
          <div class="panel-body">
            <?php echo $msg; ?>
            <form role="form" method="post" action="login.php">
              <div class="form-group">
                <label for="email">Email address</label>
                <input type="email" class="form-control" id="email" name="email" placeholder="Enter email">
              </div>
              <div class="form-group">
                <label for="password">Password</label>
                <input type="password" id="password" class="form-control" name="password">
              </div>

              <button type="submit" class="btn btn-default">Submit</button>
            </form>
          </div>
        </div>
      </div>
    </div>
  </body>

</html>

对于“$q”变量,你应该使用php sha1函数:

 $q = "select * from users where email = '$_POST[email]' and password = '" . sha1($_POST[password]) . "'";

但正如 Fred-ii 所说,您之前确实应该(必须)保护您的变量。 例如:

$_POST['email'] = mysqli_real_escape_string($_POST['email']);

它将保护您的变量免受 SQL 注入 (https://php.net/manual/en/mysqli.real-escape-string.php)