-2

I have a column passwd that I have encrypted with the algorithm PASSWORD(). I want to compare the password that a user has put in with the variable that is stored in the database. I want to encrypt the value first in another variable and the compare them.

I change the column like this:

UPDATE customer SET passwd_enc=PASSWORD(passwd);

I do the login like this:

<?php
$u = $_REQUEST['username'];
$p = $_REQUEST['pass'];

$sql="SELECT * FROM customer WHERE uname=? AND  passwd_enc=?";
if(! $stmt = $mysqli->prepare($sql)) {
    echo "Error: " . $mysqli->error;
}else( $stmt = $mysqli->prepare($sql)) {
    $stmt->bind_param("ss", $u,$p);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();

    if($row['uname']==$u && $row['passwd_enc']==$p) {
        print "Welcome $u";
        $_SESSION['username'] = $u;

    } else {
        print "Unknown user";
        $_SESSION['username'] = '?';
    }

    if($row['is_admin']==1){
        $_SESSION['is_admin']='admin';
    }else{
        $_SESSION['is_admin']='user';
    }
}
?>

Something like this:

$p=$_REQUEST['pass'];
$p_enc=encrypt($p);
if($p==(encrypted variable in db))

NOTE: I want the encyption to be done like the PASSWORD() function.

STaefi
  • 4,297
  • 1
  • 25
  • 43

1 Answers1

0

As suggested in the comments you can use password_hash() and pasword_verify(). Store the result of password_hash($plainTextPassword, PASSWORD_BCRYPT) in your database. Then check instead of checking it like

$p=$_REQUEST['pass'];
$p_enc=encrypt($p);
if($p==(encrypted variable in db))

Check it like this:

if (password_verify($_REQUEST['pass'], $encryptedVariableFromDB)){
  // Do stuff.
}

Note that:

  1. You don't have to use PASSWORD_BCRYPT, I added it to show that that parameter is available. To quote the manual: "Note that this constant [i.e. PASSWORD_DEFAULT] is designed to change over time as new and stronger algorithms are added to PHP."
  2. You talk about encryption in your answer. You actually want to hash the password instead of encrypting it.
Niellles
  • 868
  • 10
  • 27