How to verify an encrypted password during Login?

Asked

Viewed 1,293 times

1

When I try to log in:

  • if I use the wrong username and password, only the contents of the header and of footer.

  • if I use the correct username and password, the login does not recognize the user:
    "Wrong username and password".

    <?php
    $page = 'Login';
    session_start();
    include 'header.php';
    
    if(isset($_SESSION['username'])){
    header('location: control-painel.php'); 
    }
    else{
    
    $user_error = '';
    $pass_error = '';
    $login_error = '';
    
    if(isset($_POST['login'])){
    
    $username = $mysqli -> $_POST['username'];
    $password = $mysqli -> $_POST['password'];
    $cost = '11';
    $salt = 'Cf1f11ePArKlBJomM0F6aJ';
    $password_hash = crypt($password, '$2a$' . $cost . '$' . $salt . '$');
    $id = 0; 
    
    if(empty($username)){
        $user_error = 'Please insert a username';
    }
    if(empty($password)){
        $pass_error = 'Please insert a password';
    }
    if(!empty($username) && !empty($password)){
    
        $stmt = $mysqli -> prepare('SELECT id FROM user WHERE username = ? AND password = ?');
        $stmt -> bind_param("ss", $username, $password_hash);
        $stmt -> execute();
        $stmt -> bind_result($id);
        $stmt -> fetch();
    
        if($id){
            $login_error = 'Wrong username and password combination';
        }
    }
    }
    if(empty($user_error)&& empty($pass_error)&& empty($login_error)&& isset($_POST['login'])){
    
    $stmt = $mysqli -> prepare('SELECT id FROM user WHERE username = ? AND password = ?');
    $stmt -> bind_param("ss", $username, $password_hash);
    $stmt -> execute();
    $stmt -> bind_result($id);
    $stmt -> fetch();
    
    if($id){        
        session_start();
        $_SESSION['username'] = $username;
        header('location: control-painel.php');
    }
    }
    else{
    ?>
    
    <div class="message">
    <br><br>
    <?php echo $user_error; ?><br><br>
    <?php echo $pass_error; ?><br><br>
    <?php echo $login_error; ?><br><br>
    <br><br>
    </div>
    <div id="form" class="bradius">
    <div class="content">
        <form method="post">
            <label>Username: </label>
            <input type="text" name="username" class="text bradius">
            <label>Password: </label>
            <input type="password" name="password" class="text bradius">
            <input type="submit" class="submitbutton bradius" name="login" value="Login">
        </form>
    </div>
    

    <?php
       }
    }
    include "footer.php";
    ?>
    
  • Check out this post: http://blog.thiagobelem.net/encryptando-passwords- no-php-usando-bcrypt-blowfish/

  • I’ve seen him before but I don’t understand the verification part.

  • 1

    You encrypt the password typed in login exactly the same way you did in signup (in the registration) and makes a simple comparison.

  • Get this message from where? Nothing you posted indicates that this should happen. Post something else that might give us a better idea of what you’ve done.

  • 1

    To test, just try taking the value of the field password, print it and print the $password_hash to have a visual assessment of the difference between them. You are sure that you are creating the $password_hash exactly like the register?

  • You are using a variable called $password_hash, I imagined she’d been hashada exactly as on the record, as I said before. If she is saving senha321 you have a pure password, not a hash of a password. Apparently $2a11$Cf1f11ePArKlBJomM0F6aJ$ is a hash of one password, then you have to compare with another hash and not with a pure password.

  • 2

    You edited the question, but reversed the IF I put in the answer. Besides being with duplicate code unnecessarily. What I put in the question is enough, just small adjustments in the variables only. Pay attention in the IF of the original answer. Logged in is inside the IF, and wrong password inside the ELSE, not in the IF as you did. And in addition you are mixing the escape string with the bind, so you will have validation problems.

  • @Lukaz11 made some more adjustments to the code, remember to update there.

Show 3 more comments

1 answer

2


IMPORTANT This answer was given to the situation raised in the question.

Do not use crypt and salt fixed to store passwords, and in PHP use the function password_hash and password_verify for passwords.



Original response:

Hash back the password the user typed, and see if it matches the DB:

// Pego a senha do POST (adapte pro seu código)
$password = $_POST['password'];

// Aqui estamos fazendo o mesmo que você usou para encriptar. Mas dá pra melhorar isso.
$cost = '11';
$salt = 'Cf1f11ePArKlBJomM0F6aJ';
$password_hash = crypt($password, '$2a$' . $cost . '$' . $salt . '$');

// Agora comparamos o HASH da senha digitada com o HASH da senha salva
// porém, deste jeito, você está vulnerável a SQL Injection.
$mysqli->query(
   "SELECT * FROM user WHERE username = '".$username."' AND password = '".$password_hash."'"
);

See how the above code looks using bind_param, to avoid SQL Injection:

// Pego a senha do POST (adapte pro seu código)
$password = $_POST['password'];

// Inicializamos o id do usuário com 0 para usar no fetch()
$idUsuario = 0;

// Aqui estamos fazendo o mesmo que você usou para encriptar. Mas dá pra melhorar isso.
$cost = '11';
$salt = 'Cf1f11ePArKlBJomM0F6aJ';
$password_hash = crypt($password, '$2a$' . $cost . '$' . $salt . '$');

// Agora comparamos o HASH da senha digitada com o HASH da senha salva:
$query = 'SELECT id FROM user WHERE username = ? AND password = ?';
$stmt = $mysqli->prepare( $query );
$stmt->bind_param("ss", $username, $password_hash );
$stmt->execute();

// Aqui pegamos o resultado.
// se for mais de um campo, pode ser bind_result( $idusuario, $username, $email...
$stmt->bind_result( $idUsuario );
$stmt->fetch();

if ( $idUsuario ) {
   echo 'Logado';
} else {
   echo 'Usuario e/ou senha invalidos';
}

Updated answer with question edition:

Following refactoring using the principles indicated:

<?php
   $page = 'Login';
   session_start();
   include 'header.php';
   $user_error = '';
   $pass_error = '';

   if(isset($_SESSION['username'])){
      header('location: control-painel.php'); 
   } else {

      if( isset($_POST['login'])) {
         $username = $_POST['username'];
         $password = $_POST['password'];
         $cost = '11';
         $salt = 'Cf1f11ePArKlBJomM0F6aJ';
         $password_hash = crypt($password, '$2a$' . $cost . '$' . $salt . '$');
         $id = 0; 

         if(empty($username)){
            $user_error = 'Please insert a username';
         }
         if(empty($password)){
            $pass_error = 'Please insert a password';
         }

         if( empty( $user_error ) && empty( $pass_error ) ) {
            $mysqli = new mysqli//ABRIR SUA CONEXAO AQUI CASO NAO ESTEJA NO HEADER
            $stmt = $mysqli->prepare( 'SELECT id FROM user WHERE username = ? AND password = ?' );
            $stmt->bind_param( 'ss', $username, $password_hash );
            $stmt->execute();
            $stmt->bind_result( $id );
            $stmt->fetch();

            if($id){
               $_SESSION['username'] = $username;
               header('location: control-painel.php');
               die();
            } else {
               $user_error = 'User or Password invalid';
            }
         }
      }
   }
?>

<div class="message">
   <br><br>
   <?php echo $user_error; ?><br><br>
   <?php echo $pass_error; ?><br><br>
   <br><br>
</div>
<div id="form" class="bradius">
   <div class="content">
      <form method="post">
         <label>Username: </label>
         <input type="text" name="username" class="text bradius">
         <label>Password: </label>
         <input type="password" name="password" class="text bradius">
         <input type="submit" class="submitbutton bradius" name="login" value="Login">
      </form>
   </div>
</div>

<?php
   include "footer.php";
?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.