Ошибка пароля при использовании Bcrypt

До сих пор у bcrypt не было проблем. По какой-то причине следующий пароль не работает. UIO78349%^&(]\\';= Это первый раз, когда у меня не работает пароль, и я надеюсь, что у кого-нибудь есть объяснение. Я искал сеть и читал о лимите символов, но это намного ниже этого. Не уверен, что это имеет значение, но пользовательский ввод пароля проходит через mysqli_real_escape_string.

Первая партия кода, где находится форма входа:

<?php
session_start();
?>

<html>
<body>
<form method="post" action="sidebar-signin-block.php">

        <table width="90%" border="0" align="center" bgcolor="white">


            <tr>
                <td bgcolor="ffffff" colspan="2" align="center"><h2>User Login</h2></td>
            </tr>

            <tr>
                <td align="right">Email:</td>
                <td><input type="text" name="email"></td>
            </tr>

            <tr>
                <td align="right">Password:</td>
                <td><input type="password" name="password"></td>
            </tr>

            <tr>
                <td colspan="2" align="center"><input type="submit" name="login" value="Login"></td>

            </tr>

            <tr>
                <td colspan="2" align="center"><h3 style="margin-top:7px;"><a href="nonadmin_user_forgot_password.php" target="_blank" title="Reset Your Lost Password">Forgot Password?</a></h3></td>
            </tr>


            <tr>
                <td bgcolor="#ffffff" colspan="2" align="center"><div style="padding-top:5px;"><span style="font-size:20px;">Don't have an account?<br /><a href="/includes/register-user.php" title="Register with us!" target="_self">Sign Up</a> is <em>quick</em> and <em>easy</em>!</span></div></td>

        </table>
    </form>

    <?php 

// Connecting to the database and making the Bcrypt functions available
include("admin/includes/connect.php");
include ("lib/password.php");

// Gathering and sanitizing user login input
if(isset($_POST['login'])){

    $email = trim(((isset($conn) && is_object($conn)) ? mysqli_real_escape_string($conn, $_POST['email']) :((trigger_error  ("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")));

        $pass = trim(((isset($conn) && is_object($conn)) ? mysqli_real_escape_string($conn, $_POST['password']) : ((trigger_error   ("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")));

         // Checking the database records for the user login input
        $hash_query = "select nonadmin_user_pass from nonadmin_user_login where email='$email'";{
                $run_query = mysqli_query($conn, $hash_query);}
                while ($row = mysqli_fetch_assoc($run_query)) {
                $fetch_pass = $row['nonadmin_user_pass'];
                    }
        // If the user email and password matches we start a session                               
        if ((password_verify($pass, $fetch_pass)) == 1){

              // Verifying user login success with splash page then sending user back to the home page
              $_SESSION['email']=$email;
              echo "<script>window.open('login-success.php','_self')</script>";}

    // When the user login fails an alert is given to inform them
    else {
    echo "<script>alert('Email or password is incorrect please try again')</script>";
    echo "<script>window.open('index.php','_self')</script>";}  
}
?>
</body>
</html>

Здесь js.

<script>$(document).ready(function(){
$("#login").click(function(){
var email = $("#email").val();
var password = $("#password").val();
// Checking for blank fields.
if( email =='' || password ==''){
$('input[type="text"],input[type="password"]');
$('input[type="text"],input[type="password"]');
alert("Please fill all fields.");
}else {
$.post("log-me-in.php",{ email1: email, password1:password},
function(data) {
if(data=='Invalid Email.......') {
$('input[type="text"]');
$('input[type="password"]');
alert(data);
}else if(data=='Email or Password is wrong please try again.'){
$('input[type="text"],input[type="password"]');
alert(data);
} else if(data=='Successfully Logged in.'){
window.location.reload();
$("form")[0].reset();
$('input[type="text"],input[type="password"]');
alert(data);
} else{
alert(data);
}
});
}
});
});</script>

Здесь вызывается php:

<?php 
session_start();
// Connecting to the database and making the Bcrypt functions available
include("admin/includes/connect.php");
include ("lib/password.php");

$email=$_POST['email1']; // Fetching Values from URL.
$password= ($_POST['password1']); 
// check if e-mail address syntax is valid or not
//$email = filter_var($email, FILTER_SANITIZE_EMAIL); // sanitizing email(Remove unexpected symbol like <,>,?,#,!, etc.)
//if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
//echo "Invalid Email.......";
//}else{
// Matching user input email and password with stored email and password in database.
$result = mysqli_query($conn, "SELECT * FROM nonadmin_user_login WHERE email='$email'");
$data = mysqli_fetch_array($result);
$bcrypt_pass = $data['nonadmin_user_pass'];
$email_match = $data['email'];

if (password_verify ($password, $bcrypt_pass) == 1 AND $email == $email_match) {

$_SESSION['email']=$email;
echo "Successfully Logged in.";
}

else{
echo "Email or Password is wrong please try again";
}

//}
?>

Here is the user registration code where the password initially gets entered before mail verification:

    <html>
    <head>
    <title>Register at Recycling Kansas City</title>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="/styles/register-user.css" media="all">

    <!-- ie compatibility -->
    <!--[if IE]>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <![endif]-->

    <!--[if lt IE 9]>
    <script src="Site/javascript/bootstrap/html5shiv.js"></script>
    <![endif]-->

    <meta content="recycling kansas city, recycling centers, recycling locations" name="keywords">
    <meta content="Recycling Kansas City is an efficient resource to help you quickly find a recycle center that is nearby. Use our map to find locations and accepted items." name="description">
         </head>



    <h1 class="center">Why register at Recycling Kansas City?</h1>

    <p>By registering here you will gain access to additional features. Once registered you can create your own custom profile, submit and comment on blog articles, advertise your products or services and have the choice to opt in for email announcements.</p>

    <p>All of your information will be securely stored in our database and you can delete your account at any time. Also, rest assured that we will never share any of your submitted details with anyone ever.</p>

    <form method="post" action="register-user.php">

            <table width="520" border="10" align="center" bgcolor="white">


                <tr>
                    <td bgcolor="ffffff" colspan="2" align="center"><h1>Registration</h1></td>
                </tr>

                <tr>
                    <td align="right">Email</td>
                    <td><input type="text" name="email" size="53"></td>
                </tr>

                <tr>
                    <td align="right">Password:</td>
                    <td><input type="password" name="pwd" size="53"></td>
                </tr>
                <tr>
                    <td align="right">User Name:</td>
                    <td><input type="text" name="name" size="53"></td>
                </tr>

                <tr>
                    <td colspan="2" align="center"><input type="submit" name="register" value="Register"></td>
                </tr>

            </table>
        </form>
    </html>



    <?php

    include ("../admin/includes/connect.php");
    include ("../lib/password.php");

    $con = new mysqli("localhost", "$username", "$password", "$database");

    /* check connection */
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }

    if(isset($_POST['register'])){

    $email = trim(mysql_escape_string($_POST['email']));

    $nonadmin_user_pass = trim(mysql_escape_string($_POST['pwd']));

    $password = password_hash($nonadmin_user_pass, PASSWORD_BCRYPT);

    $nonadmin_user_name = trim(mysql_escape_string($_POST['name']));

    $query_verify_email = "SELECT * FROM nonadmin_user_login WHERE email ='$email' and verified = 1";

    $verified_email = mysqli_query($con,$query_verify_email);

    if (!$verified_email) {

    echo ' System Error';
    }

    if (mysqli_num_rows($verified_email) == 0) {

    // Generate a unique code:

    $hash = md5(uniqid(rand(), true));

    $query_create_user = "INSERT INTO `nonadmin_user_login` (`email`, `nonadmin_user_pass`, `nonadmin_user_name`,  `hash`) VALUES ('$email', '$password', '$nonadmin_user_name', '$hash')";

    $created_user = mysqli_query($con,$query_create_user);

    if (!$created_user) {

    echo 'Query Failed ';
    }

    if (mysqli_affected_rows($con) == 1) { //If the Insert Query was successfull.

    $subject = 'Activate Your Email';

    $headers = "From: [email protected] \r\n";

    $headers .= "MIME-Version: 1.0\r\n";

    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

    $url= 'http://recyclingkansascity.com/includes/register-verify.php?email=' . urlencode($email) . "&key=$hash";

    $message ='<p>To activate your account please click on Activate buttton</p>';

    $message.='<table cellspacing="0" cellpadding="0"> <tr>';

    $message .= '<td align="center" width="300" height="40" bgcolor="#000091" style="-webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px;

    color: #ffffff; display: block;">';

    $message .= '<a href="'.$url.'" style="color: #ffffff; font-size:16px; font-weight: bold; font-family: Helvetica, Arial, sans-serif; text-decoration: none;

    line-height:40px; width:100%; display:inline-block">Click to Activate</a>';

    $message .= '</td> </tr> </table>';

    mail($email, $subject, $message, $headers);

    echo '<p class="center">A confirmation email

    has been sent to <b>'. $email.' </b></p><p class="center">Please <strong>click</strong> on the <strong><em>Activate</em> Button</strong> to Activate your account.</p> ';

    } else { // If it did not run OK.

    echo '<div>You could not be registered due to a system

    error. We apologize for any

    inconvenience.</div>';

    }

    }

    else{

    echo '<div>Email already registered</div>';}

    }
    ?>

До сих пор ни разу не возникало проблем с паролем, пока пароль в начале поста? Странно, если вы спросите меня.


person Disaster Faster    schedule 17.03.2015    source источник
comment
Думаю, нам понадобится код для отладки этой проблемы.   -  person Ryan Bigg    schedule 17.03.2015
comment
Удалите все вызовы mysqli_real_escape_string() для ввода пароля, функции password_hash() и password_verify() принимают даже двоичный ввод и не подвержены SQL-инъекциям. Я предполагаю, что это уже решает вашу проблему. Тогда функция password_verify() уже возвращает логическое значение, не нужно сравнивать его с == 1. Если это не решит вашу проблему, я бы убедился, что каждая страница использует UTF-8 в качестве формата файла и определила его в заголовке.   -  person martinstoeckli    schedule 17.03.2015
comment
martinstoeckli большое спасибо за вклад! Я внес предложенные вами изменения, и теперь он работает как сон. Ваш экспертный вклад очень ценится! Я просто попытался пометить вопрос как ответ, но не смог найти нужный ответ? Любые предложения, как пометить этот вопрос как отвеченный?   -  person Disaster Faster    schedule 17.03.2015
comment
@DisasterFaster - рад, что идентификатор сработал. Вы не можете пометить его как отвеченный, потому что это всего лишь комментарий. Я добавил это как ответ сейчас.   -  person martinstoeckli    schedule 18.03.2015
comment
Спасибо, martinstoeckli, и я проголосовал за него и отметил его ответом. Большое спасибо за вашу помощь.   -  person Disaster Faster    schedule 18.03.2015


Ответы (1)


Удалите все вызовы mysqli_real_escape_string() для ввода пароля, функции password_hash() и password_verify() принимают даже двоичный ввод и не подвержены к SQL-инъекции. Я предполагаю, что это уже решает вашу проблему. Экранирование должно выполняться как можно позже и только для данной целевой системы, поэтому функцию mysqli_real_escape_string() следует вызывать только для построения SQL-запроса.

Тогда функция password_verify() уже возвращает логическое значение, не нужно сравнивать его с == 1.

if (password_verify($pass, $fetch_pass))
{
  ...
}

Если это не решит вашу проблему, я бы убедился, что каждая страница использует UTF-8 в качестве формата файла и определила его в заголовке.

person martinstoeckli    schedule 17.03.2015