1

I have successfully created my passwords and am inserting them into the database using CRYPT_BLOWFISH. However I do no know how to match the crypted passwords in the database to the passwords the user is entering to login. Any help is greatly appreciated thanks.

To generate the password from the users input I use:

REGISTER.PHP

//If there are no errors or returned_records and the form is submitted let's submit the info and register the user
else if(!$error_msg && !$returned_record && $_POST['register']){
    //Place the newly hased/encrypted password into our new_password variable
    function generateHash($password_1){
    if(defined("CRYPT_BLOWFISH") && CRYPT_BLOWFISH){
        $salt = '$2y$11$'. substr(md5(uniqid(rand(), true)), 0, 22);
        return crypt($password_1, $salt);
     }//End If
    }//End Function genrateHash*/                   
    $new_password = generateHash($password_1);  
    $pass = $new_password;

    //Build our query
   $sql = ("INSERT INTO members (username, email, password_1) VALUES (?,?,?)");
    //Prepare our query
    $stmt = $mysqli->prepare($sql) or die("Failed Execution");
    //Bind the fields and there paramters to our query
    $stmt->bind_param('sss', $username, $email, $new_password);
    //Execute the query
    $stmt->execute();
    echo $stmt->error;
    header('Location: http://www.yourschoolsincanada.com/english/register/registration-success/');
    exit();
}

LOGIN.PHP

if(isset($_POST['login'])){
$username = $_POST['username'];
$password_1 = $_POST['password_1'];

$sql = "SELECT member_id, username, password_1 FROM members WHERE username = ? AND password_1 = ? LIMIT 1";
//Prepare our query
if($stmt = $mysqli->prepare($sql)){
    //Bind the Parameters to the query
    $stmt->bind_param('ss', $username, $password_1);

    //Execute the query
    $result = $stmt->execute();
    /*Store our result to get properties*/
    $stmt->store_result();          
    //Get the number of rows
    $num_of_rows = $stmt->num_rows;     

    //Bind the results of what the query gave us to our three variables
    $stmt->bind_result($id, $username, $password_1);


    if(crypt($password_1, $pass) == $pass){
        echo "Match";
    }
    else{
        echo "Passwords don't match";
    }   
}
bilcker
  • 1,120
  • 1
  • 15
  • 43
  • 2
    If you are using PHP 5.5 consider `password_hash` and `password_verify` instead. – Jon Mar 13 '14 at 20:11
  • @Jon is right - even if you're below 5.5 but equal to or above 5.3.7 you can use [password_compat](https://github.com/ircmaxell/password_compat) to get that functionality, per the [PHP.net Safe Password Hashing FAQ](http://www.php.net/manual/en/faq.passwords.php) entry. – Anti-weakpasswords Mar 15 '14 at 02:35

1 Answers1

1

Working Demo

I've gotten the following to work. The HTML form and PHP all run inside the same page.

<?php
DEFINE ('DB_USER', 'xxx');
DEFINE ('DB_PASSWORD', 'xxx');  
DEFINE ('DB_HOST', 'xxx');
DEFINE ('DB_NAME', 'xxx');

$mysqli = @mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) 
OR die("could not connect");

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

    $username = htmlentities(trim($_POST['username']));
    $username = mysqli_real_escape_string($mysqli, $username);
    $password = trim($_POST['password']);
    $query = mysqli_query($mysqli, "SELECT username, password_1 FROM members WHERE username = '$username'");
    $row = mysqli_fetch_assoc($query);
    $numrows = mysqli_num_rows($query);
    $dbuser = $row['username'];
    $dbpass = $row['password_1'];
    $hashed_password = crypt($password, $dbpass);

// var_dump($dbuser); // For testing purposes only, can be removed
echo "<hr>";
// var_dump($dbpass); // For testing purposes only, can be removed

    if( ($username == '') || ($password == '') ) {
        $error_string = '<font color=red>You have left either the username or password field blank!</font>';
echo $error_string;
        }
    if ($numrows == 0)
    {
        $error_string = '<font color=red>No username can be found!</font>';

echo $error_string;

        }
    else if ($numrows == 1)
    {

if ($hashed_password == $dbpass)
       {
       $error_string = '<font color=red>Details checked out</font>';

echo $error_string;

       }
    }
    else {
            $error_string = '<font color=red>There was an error. Please contact an Admin</font>';
echo "SORRY Charlie!";
    }

 } // brace for isset login
?>

<form action="" method="post">
Username: 
<input type="text" name="username">
<br>
Password: 
<input type="text" name="password">
<br>
<input type="submit" name="login" value="Submit">
</form>

Original answer

The following should work, since I've gotten a "match" using the following inside the same file.

Read the comments inside the code.

<?php
$password_1 = "1234567890"; // User-entered password

function generateHash($password_1){
    if(defined("CRYPT_BLOWFISH") && CRYPT_BLOWFISH){
       $salt = '$2y$11$'. substr(md5(uniqid(rand(), true)), 0, 22);
    return crypt($password_1, $salt);
    }
} 


// Remove the echo. For testing purposes only
echo $new_password = generateHash($password_1);

$pass = $new_password;

echo "<br>";
echo $pass;
echo "<hr>";

// Verify that the password matches and use in your login page
// Syntax: if(crypt($password_entered, $password_hash) == $password_hash)

    if(crypt($password_1,$pass) == $pass) {

    // password is correct
    echo "Match.";

    }

else {
echo "No match.";
}

EDIT

Password generator:

<?php
$password_1 = "1234567890"; // User-entered generated password
// or from a form
// $password_1 = $_POST['password']; // User-entered generated password

function generateHash($password_1){
    if(defined("CRYPT_BLOWFISH") && CRYPT_BLOWFISH){
       $salt = '$2y$11$'. substr(md5(uniqid(rand(), true)), 0, 22);
    return crypt($password_1, $salt);
    }
} 

// here you can enter the password into DB
// since we have a successful echo
// Remove the echo. For testing purposes only
echo $new_password = generateHash($password_1);

$pass = $new_password;

echo "<br>";
echo $pass;
echo "<hr>";

Login check:

$password_1 = $_POST['password']; // User-entered password

// DB codes example:
$query = mysqli_query($con, "SELECT password FROM users WHERE password='".$password_1."'");

// Verify that the password matches and use in your login page
// Syntax: if(crypt($password_entered, $password_hash) == $password_hash)

    if(crypt($password_1,$pass) == $pass) {

    // password is correct
    echo "Match.";

    }

else {
echo "No match.";
}
Community
  • 1
  • 1
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
  • sorry if this seems dumb but I understand how that works but I am having a lot of trouble wrapping my head around how I can get the variable $pass into my login page so it is recognized with the hash from the registration page. does that make sense? – bilcker Mar 14 '14 at 14:49
  • It's not dumb at all; I can understand that it could seem complicated. The `$password_1 = "1234567890";` would come from your form; i.e.: `$password_1 = $_POST['password'];` then you could use the code starting from `if(crypt($password_1,$pass) == $pass)...` into your login PHP code. If what has been entered by the user matches what's in your DB, then it should work; since that complete code was executed inside one file. @bilcker – Funk Forty Niner Mar 14 '14 at 14:55
  • I made another change and added a DB example. Reload to see the change. @bilcker – Funk Forty Niner Mar 14 '14 at 15:08
  • Thanks for your continued effort and help but it still does not match. As I don't think it recognizes $pass as the encrypted password anymore out side of the register file. I have updated my question to reflect both of my files. – bilcker Mar 14 '14 at 15:32
  • To my understanding I need a way of carrying that $pass value into the login.php file as the hashed password string. is that wrong? – bilcker Mar 14 '14 at 15:34
  • It's not wrong. I placed some comments (in the code) inside my Edit to show that, if there's a successful echo, then you can enter/retrieve in DB. @bilcker – Funk Forty Niner Mar 14 '14 at 15:35
  • mhm, I must be really confused cause I still can't get it to work. No problem generating the password but It still won't match it to the user input. It seems logical and all but it doesn't – bilcker Mar 14 '14 at 17:11
  • I'll have a look at your (edit) code when I get a chance. I'll see what I can do for you. @bilcker I will keep you posted. However, I might need to know what's above your `else if(!$error_msg && !$returned_record && $_POST['register']){` in `REGISTER.PHP` – Funk Forty Niner Mar 14 '14 at 20:19
  • @bilcker Reload my answer, and look on top under **Working Demo**, which worked for me; I set up a DB just for it. – Funk Forty Niner Mar 14 '14 at 23:55
  • 1
    You have went above and beyond helping me, thank you so much. It is working, I am going to modify to work with prepared statements. Thanks again you rock. – bilcker Mar 17 '14 at 13:55
  • You're very much welcome and I was glad to help in order to find a solution for you. I have a similar script that uses `crypt()` yet with a different salt and a different login method. I was able to piece both together (*with some doing hahaha!*). Work with a "copy" of it, so if anything goes funny on you, you will have a backup ;-) @bilcker -- And/or, you can always resort/revert back to my answer, cheers! – Funk Forty Niner Mar 17 '14 at 14:00