Member Avatar for roxanne.martos

im working on my login script and whilst testing it, it seems that the code doesnt recognise the details stored within a database im entering a valid username and password in the login form but it is not processing it somehow the system thinks its wrong. I cant find any more errors i am running an error report function and nothing appears i cant seem to figure out where the problem is

<?php
error_reporting(E_ALL);
include_once("conninfo2.php");

if(isset($_POST['username']) && trim($_POST['username']) != ""){
    $username = strip_tags($_POST['username']);
    $password = $_POST['password'];
    $hmac = hash_hmac('sha512', $password, file_get_contents('textfiles/key.txt'));
    $stmt1 = $db->prepare("SELECT usersid, password FROM login WHERE username=:username AND activated='1' LIMIT 1");
    $stmt1->bindValue(':username',$username,PDO::PARAM_STR);
    try{
        $stmt1->execute();
        $count = $stmt1->rowCount();
        if($count > 0){
            while($row = $stmt1->fetch(PDO::FETCH_ASSOC)){
                $uid = $row['usersid'];
                $hash = $row['password'];
            }
            if (crypt($hmac, $hash) === $hash) {
                $db->query("UPDATE login SET lastlog=now() WHERE usersid='$uid' LIMIT 1");
                $_SESSION['uid'] = $uid;
                $_SESSION['username'] = $username;
                $_SESSION['password'] = $hash;
                setcookie("usersid", $uid, strtotime( '+30 days' ), "/", "", "", TRUE);
                setcookie("username", $username, strtotime( '+30 days' ), "/", "", "", TRUE);
                setcookie("password", $hash, strtotime( '+30 days' ), "/", "", "", TRUE); 
                 echo 'Valid password<br />'.$_SESSION['uid'].'<br />'.$_SESSION['username'].'<br />'.$_SESSION['password'].'
                <br />'.$_COOKIE['usersid']; 
                /*header("location: index.php");*/
                exit();
            } else {
                echo 'Invalid password Press back and try again<br />';
                exit();
            }
        }
        else{
            echo "A user with that email address does not exist here";
            $db = null;
            exit();
        }
    }
    catch(PDOException $e){
        echo $e->getMessage();
        $db = null;
        exit();
    }
}
?>

Recommended Answers

All 16 Replies

From which point up is it going wrong? Is the user with the given username even being retrieved? Or does shit hit the fan when you compare the given password with the password in the database?

Member Avatar for roxanne.martos

from what i can gather it is the password i would have thought the username but when i tested it the username was the same as the database so the password is the issue for now

And have you validated that the password that you are submitting through the form is actually the same as the one in the database? In other words: if you KNOW the password in the database is "shoelace" and if you are also sure the submitted password is "shoelace", but if the encrypted passwords differ from each other, there must be something going wrong in your encryption process.

Member Avatar for roxanne.martos

okay so would that be in the register then as thats were the password is first set ??

Member Avatar for roxanne.martos

this is what i have to ecrypt my password

//hmac
   $hmac = hash_hmac('sha512', $password1, file_get_contents('textfiles/key.txt'));

   //bytes for salt
   $bytes = mcrypt_create_iv(16, MCRYPT_DEV_URANDOM);

   //salt
   $salt = strtr(base64_encode($bytes), '+', '.');

   //make bcrypt 22 characters
   $salt = substr($salt, 0, 22);

   //hashed password
   $bcrypt = crypt($hmac, '$2y$12$' . $salt);
   $token = md5($bcrypt);

Yes I guess that would be it, then :). Check if the password that is inserted during the registration process is the same as the one that is checked against during the login process (by checking if the encrypted values of the exact same password is the same in both places).

Member Avatar for roxanne.martos

hi they seem to be the same i just created a new account and copied the password over onto the login and im still recieving invalid password. Is that what you meant i needed to do?

I guess so. In your script above you are doing the following:

$password = $_POST['password'];
$hmac = hash_hmac('sha512', $password, file_get_contents('textfiles/key.txt'));

And then you compare the given password to the one in the database as follows:

if(crypt($hmac, $hash) === $hash)
{
    // Login info is correct.
}

Are you using the exact same way of encrypting the user's password when he registers? So is the encrypted password that is generated during the reigstration process the same as the encrypted password that is generated during the login process?

Member Avatar for roxanne.martos

yes i have those elements within the login also except that they are separted i have the $password post and hmac at the top and the if crypt within the staement execute. sorry if im being dumb ive been looking at this code for days now

if(isset($_POST['username']) && trim($_POST['username']) != ""){
        $username = strip_tags($_POST['username']);
        $password = $_POST['password'];
        $hmac = hash_hmac('sha512', $password, file_get_contents('textfiles/key.txt'));
        $stmt1 = $db->prepare("SELECT usersid, password FROM login WHERE username=:username AND activated='1' LIMIT 1");
        $stmt1->bindValue(':username',$username,PDO::PARAM_STR);
        try{
            $stmt1->execute();
            $count = $stmt1->rowCount();
            if($count > 0){
                while($row = $stmt1->fetch(PDO::FETCH_ASSOC)){
                    $uid = $row['usersid'];
                    $hash = $row['password'];
                }
                if (crypt($hmac, $hash) === $hash) {
                    $db->query("UPDATE login SET lastlog=now() WHERE usersid='$uid' LIMIT 1");
                    $_SESSION['uid'] = $uid;
                    $_SESSION['username'] = $username;
                    $_SESSION['password'] = $hash;
                    setcookie("usersid", $uid, strtotime( '+30 days' ), "/", "", "", TRUE);
                    setcookie("username", $username, strtotime( '+30 days' ), "/", "", "", TRUE);
                        setcookie("password", $hash, strtotime( '+30 days' ), "/", "", "", TRUE); 
                     echo 'Valid password<br />'.$_SESSION['uid'].'<br />'.$_SESSION['username'].'<br />'.$_SESSION['password'].'
                    <br />'.$_COOKIE['usersid']; 
                    /*header("location: index.php");*/
                    exit();
                } else {
                    echo 'Invalid password Press back and try again<br />';
                    exit();
                }
            }
            else{
                echo "A user with that email address does not exist here";
                $db = null;
                exit();
            }
        }

You don't seem to be using strtoupper() or strtolower() when checking the username. That would mean that the username needs to be input exactly as it was during signup. E.g.: If they sign up with the username "MyUsername" then try to log in with "myusername" it would fail because it doesn't match the database.

What I do with login scripts is allow the user to input their username in whatever case they want during sign up so their username could be "MyUsername" but then let them log in by typing it in any case. When checking it against the username held in the database, it would compare them both in lowercase.

Well then can't really think of another way to find out what's going wrong :. What I would do is:

  1. Check until where the script runs (is the while() loop reached, is the required if() loop reached?).
  2. Depending on where the script is halted, check what is causing the halt/discontinuation.
  3. In your case that seems to be a faulty password match. This means that we must validate that the password that is given through the form, encrypted, SHOULD match the password in the database, and if it doesn't, why it doesn't. I would try something like:

(register.php)

$password = $_POST['password'];

echo '<pre>$password is now: ' . htmlentities($password) . '</pre>';

// Encrypt your password here.

echo '<pre>$encrypted_password is now: ' . htmlentities($encrypted_password) . '</pre>';

(the same goes for your login.php page)

$password = $_POST['password'];

echo '<pre>$password is now: ' . htmlentities($password) . '</pre>';

// Encrypt your password here.

echo '<pre>$encrypted_password is now: ' . htmlentities($encrypted_password) . '</pre>';

If both the submitted password and the encrypted password are exactly the same on both pages, the problem apparently lies not in your encryption process, but somewhere else.

Also, the error you should be getting right now is the Invalid password Press back and try again<br /> error. Is that the one you're getting?

Member Avatar for roxanne.martos

yes thats the error im getting at this moment

Member Avatar for roxanne.martos

ive just read about having to store the salt onto the database could this be the issue?

Yes it could. If you encrypt the same password using different salts, you will get different results, and thus the passwords won't match - ever.

Example:
Upon registration you use the salt "asdfjasdfp1231" to encrypt "MyPassword123". Upon logging in you use salt "@!$)@Y#$!H)@H" to encrypt that same "MyPassword123". Now, the passwords entered by the user might be the same; the encrypted passwords will differ, because you have used different salts.

(Not sure if this is what you mean, but I sure hope it is.)

Member Avatar for roxanne.martos

hi yes it is exactly my issue, how can i overcome this as i do want my logi passwords to be encrypted too

Upon registration, you save the salt that was used to encrypt the password, and you retrieve it upon login to encrypt the password again with that same salt. At least, that is for as far as I know it works.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.