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

时间:2015-05-23 14:38:03

标签: php mysql encryption phpmyadmin sha1

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

当我在数据库中使用值运行“$ q”时,它会返回结果。但即使在输入正确的凭据后通过脚本,我也无法登录。此外,如果我在两个地方(脚本和数据库)删除加密,它工作正常。如果我使用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>

1 个答案:

答案 0 :(得分:1)

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

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

但正如弗雷德二世所说,你之前真的要(必须)保护你的变量。 例如:

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

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

的影响