0

I'm struggling with an aspect of something I am trying to do. I am trying to create a basic password management system but I cannot login with an encrypted password. The password does get encrypted on the DB after using the account management page, but when I log out and try to log back in it no longer works.

Here is my code for the login page and change password page: I am aware that SQL injection is a problem but I haven't got round to sorting that part out yet.

LOGIN2.PHP

    <link rel="stylesheet" type="text/css" href="default.css" media="screen"/>
    <?php 
     session_start();
    $dbname = "obsidian";

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



        //encryption for salt---------------------------------

        function makeSalt($salt_length)
        {   // only these characters are allowed in salt strings
        $saltset = './0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

        // note that this method only allows up to 6 duplicate chars
        $saltchar = "$saltset$saltset$saltset$saltset$saltset$saltset";
        // shuffles string randomly & grabs 1st n for our salt
        $salt = substr(str_shuffle($saltchar), 0, $salt_length);

        return $salt;
        }

        //Login Script


        $username = $_POST['username'] ; 
        $password = $_POST['password'] ;

        //ENCRYPTS THE USER ENTERED PASSWORD

        $salt = '$5$rounds=1000$' . makeSalt(16) . '$';
            $hashed_password = crypt($password, $salt);

        //CONNECT TO DB

        $mysqli = new mysqli('localhost','admin1', 'password1','obsidian' ) or die('Failed to connect to DB' . $mysqli->error );

        $sSQL = "select * from users where password='$hashed_password' AND username='$username'";

        $result = mysqli_query( $mysqli, $sSQL);

        if (!$sSQL) {
            printf("Error: %s\n", mysqli_error($con));
            exit();
        }

        $row = mysqli_fetch_array($result);


        if(!$row){
            echo "<div>";
            echo "No existing user or wrong password.";
            echo "</div>";
            session_destroy();
            header("Location: index.php");
        }

        else {  

            $_SESSION['userid'] =$username; 


            header("Location: index.php"); 

        }


     }

   ?>

And this is the PHP script for the changing of passwords.

<?php 



 session_start();
$dbname = "obsidian";

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


    //CREATE SALT-------------------------------------------------------------------------

    function makeSalt($salt_length)
    {   // only these characters are allowed in salt strings
    $saltset = './0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    // note that this method only allows up to 6 duplicate chars
    $saltchar = "$saltset$saltset$saltset$saltset$saltset$saltset";
    // shuffles string randomly & grabs 1st n for our salt
    $salt = substr(str_shuffle($saltchar), 0, $salt_length);
    return $salt;
    }


    //Entered credentials from form---------------------------------------------------------

    $oldPass = $_POST['oldPass'];
    $newPass = $_POST['newPass'];
    $newPassAgain = $_POST['newPassAgain'];


    //Connect to DB-------------------------------------------------------------------------------

    $mysqli = new mysqli('localhost','admin1', 'password1','obsidian' ) or die('Failed to connect to DB' . $mysqli->error );


    //CHECK IF OLD PASS AND SESSION ID EQUAL-----------------------------------------------------

    $sSQL = ("select * from users WHERE password='$oldPass' AND username= '" . $_SESSION["userid"] . "'");

     $result = mysqli_query( $mysqli, $sSQL);


    if (!$sSQL) 

      {
           printf("Error: %s\n", mysqli_error($con));
           exit();
      } 


   $row = mysqli_fetch_array($result);

    //IF THERE ARE NO ROWS, DO NOT CHANGE PASSWORD-------------------------------------------

    if(!$row)

      {
           echo "<div>";
           echo "No existing user or wrong password.";
           header("Location: account.php");
           echo "</div>";
           session_destroy();
      }


    //IF THERE ARE ROWS ENCRYPT AND CHANGE PASSWORD---------------------------------------- 

    else {


        $salt = '$5$rounds=1000$' . makeSalt(16) . '$';
        $hashed_password = crypt($password, $salt);



        if ($newPass == $newPassAgain){
        $update = ("UPDATE users SET password = '$hashed_password' where username= '" .               $_SESSION["userid"] . "'") or die (mysql_error());

        if ($mysqli->query($update) === TRUE) {
            echo "Record updated successfully";
            header("Location: success.php");
        } 

        else {
            echo "Error updating record: " . $mysqli->error;
        }

    }       
}

}   

A point in the right direction would be appreciated.

Thanks

2
  • Please differentiate between encryption and hashing. Encryption can be reversed, hashing cannot. You hash passwords, not encrypt them. Commented Nov 30, 2014 at 10:27
  • Your code is vulnerable to SQL injections. You should read on how to prevent them in PHP. Commented Nov 30, 2014 at 10:30

2 Answers 2

1

You are hashing a password with a random salt each time.

Example code:

echo makeSalt(16) . "\n";
echo makeSalt(16) . "\n";
echo makeSalt(16) . "\n";

Outputs:

oAv0cGIzTECgF1gI
ypZegnQoS.d/inqA
6PPXZ/.YfupGuxPg

In order for the hash to be the same, the salt has to be the same. Though having the same salt for every user is not as secure as having a different hash for every user. You could for example consider making the salt based on the username, or store the salt and the hash and then select the salt and encrypted password from the database for the user who is attempting to login. Then the hash should match if you hash the supplied password with the same salt.

Furthermore, consider using sha_512 instead of sha__256. ($5$ -> $6$). Also consider using mysqli or PDO as you will have more secure queries (Less chance on mysql injections).

(Pseudoish code)

(Insert code)
$salt = '$6$rounds=1000$' . makeSalt(16) . '$';
$hashed_password = crypt($password,$salt);
insert into table (password_salt,password_hash...) values($salt,$hashed_password,.....);

(Verify code)
select password_salt, password_hash.... from table where user = username
if(hash_equals(crypt($password,$password_salt),$password_hash)){
  //OK
}else{
  //Wrong password!
}
Sign up to request clarification or add additional context in comments.

Comments

0

Your encryption system is safe and secure just as this

$user_input = "someone";
$pass_input = "something";
$auth_credentials = hash("sha512", md5(sha1(md5($user_input . $pass_input))));
echo $auth_credentials;

test and feedback.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.