PHP Login Script - hashed & salted password not matching

  • (2 Pages)
  • +
  • 1
  • 2

24 Replies - 10058 Views - Last Post: 11 May 2012 - 08:08 PM Rate Topic: -----

#1 Cynosure  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 44
  • Joined: 04-February 09

PHP Login Script - hashed & salted password not matching

Posted 23 April 2012 - 02:53 PM

Hey there!

I promise this isn't for a class.. I was simply following the tutorial from http://tinsology.net...m-the-right-way for fun.

I've done everything correctly, according to the tutorial. However, when my "login.php" file checks the password in the database against the password entered in the login form it says they don't match and I constantly get thrown to the "wrongpassword.html" page. I've tried tinkering it with a lot but I am quite new to PHP (only halfway through the three books I've purchased). I even created a full new page to echo out each of the values and they matched. I'm very confused.

The lines that shoot me to the "wrongpassword.html" page are from lines 28-32. I've also included "registration.php" file which does what it's supposed to.

login.php
<?php
//user login

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


//database
			$dbhost = 'localhost';
			$dbname = 'loginScript';
			$dbuser = 'root';
			$dbpassword = '';
			
				//connect
					$connect = mysql_connect($dbhost, $dbuser, $dbpassword);
					mysql_select_db($dbname, $connect);
					
$username = mysql_real_escape_string($username);
$query = "SELECT password, salt FROM users WHERE username = '$username';";
$result = mysql_query($query);

	//no such user
	if(mysql_num_rows($result) < 1){
		header('Location: index.html');}
		
	$userData = mysql_fetch_array($result, MSQL_ASSOC);
	$hash = hash('sha256', $userData['salt'] . hash('sha256', $password) );
		//invalid password
		if($hash != $userData['password']){
			header('Location: wrongpassword.html');}
		else
			header('Location: success.html');








register.php
<?php
//register user

$username = $_POST['username'];
$password1 = $_POST['password1'];
$password2 = $_POST['password2'];
$fname = $_POST['fname'];
$sname = $_POST['sname'];
$uin = $_POST['uin'];


//check passwords =
	if($password1 != $password2)
		header('Location: register.html');
//check lengths
	if(strlen($username) > 30)
		header('Location: register.html');

	if(strlen($fname) > 15)
		header('Location: register.html');

	if(strlen($sname) > 25)
		header('Location: register.html');
		
	if(strlen($uin) > 7)
		header('Location: register.html');
//check uin is int
	if(ctype_digit($uin)){
			
			//hash password
				$hash = hash('sha256', $password1);
			
			//salt hash
				function Salt(){
					$string = md5(uniqid(rand(), true));
					return substr($string, 0, 3);
				}
				
				$salt = Salt();
				$hash = hash('sha256', $salt . $hash);
				
				
				
			//database
			$dbhost = 'localhost';
			$dbname = 'loginScript';
			$dbuser = 'root';
			$dbpassword = '';
			
				//connect
					$connect = mysql_connect($dbhost, $dbuser, $dbpassword);
					mysql_select_db($dbname, $connect);
					
					$username = mysql_real_escape_string($username);
					
					$query = "INSERT INTO users ( username, password, salt, fname, sname, uin )
							 VALUES ( '$username', '$hash', '$salt', '$fname', '$sname', '$uin' );";
					mysql_query($query);
					mysql_close();
					
					header('Location: index.html');
		}
		
		else
			header('Location: register.html');





Is This A Good Question/Topic? 0
  • +

Replies To: PHP Login Script - hashed & salted password not matching

#2 Cynosure  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 44
  • Joined: 04-February 09

Re: PHP Login Script - hashed & salted password not matching

Posted 23 April 2012 - 03:03 PM

Also, these are the values inside of the database:

'password' => ad883d0ee0ebb0e299d8f2a62b737c38c75fd29460986e7d05cf8c3b40c4044f
'salt' => 8cf
Was This Post Helpful? 0
  • +
  • -

#3 creativecoding  Icon User is offline

  • Hash != Encryption
  • member icon


Reputation: 927
  • View blog
  • Posts: 3,209
  • Joined: 19-January 10

Re: PHP Login Script - hashed & salted password not matching

Posted 23 April 2012 - 03:04 PM

I don't see why you would even store your salt inside of a database. I mean, the whole reason for a salt is so that if your database is compromised, it would make it almost impossible to use something like rainbow tables and figure out the password.

On top of that you're limiting your salt to 3 characters. It's best to keep it longer.

You're also just begging for an SQL injection, aka Bobby Tables. I would suggest using MySQLi or PDO and using prepared statements.

This post has been edited by creativecoding: 23 April 2012 - 03:09 PM

Was This Post Helpful? 3
  • +
  • -

#4 Cynosure  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 44
  • Joined: 04-February 09

Re: PHP Login Script - hashed & salted password not matching

Posted 23 April 2012 - 03:09 PM

Don't shoot the newbie! :surrender:

I've learned quite a bit from the tutorial, but I would like to finish it in order to move onto learning about sessions.

Have you any idea where the issue lies?
Was This Post Helpful? 0
  • +
  • -

#5 Cbeppe  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 31
  • View blog
  • Posts: 215
  • Joined: 16-September 09

Re: PHP Login Script - hashed & salted password not matching

Posted 23 April 2012 - 03:11 PM

Your problem is this:

In your register script, you hash your password like so:
$hash = hash('sha256', $salt . $hash);
While in your login script you hash it like this:
$hash = hash('sha256', $userData['salt'] . hash('sha256', $password)

This is a fundamental difference. If your password is "pass" and salt is "8cf", your REGISTER script will hash this string "pass8cf". Your LOGIN script on the other hand would produce this: hash("pass").hash("8cf").

Other than that, follow creativecoding's advice ;)

Edit To Add: Your solution is to pick ONE way of hashing and stick to it!

This post has been edited by Cbeppe: 23 April 2012 - 03:12 PM

Was This Post Helpful? 1
  • +
  • -

#6 Cynosure  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 44
  • Joined: 04-February 09

Re: PHP Login Script - hashed & salted password not matching

Posted 23 April 2012 - 03:19 PM

I appreciate the reply. I'm not sure I understand.

In register I have this:
$hash = hash('sha256', $password1);
$hash = hash('sha256', $salt . $hash);


Is that not equivalent to to this?
$hash = hash('sha256', $userData['salt'] . hash('sha256', $password) );


Was This Post Helpful? 0
  • +
  • -

#7 Cbeppe  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 31
  • View blog
  • Posts: 215
  • Joined: 16-September 09

Re: PHP Login Script - hashed & salted password not matching

Posted 23 April 2012 - 03:30 PM

No, it's not.

Concatenating two hashes does not produce the same result as hashing two concatenated strings. It may sound confusing, but a hashing function will produce a (fairly) unique result for every string.

In Register, you first hash the password, then you hash the hash of the password combined with the salt.

In Login, you hash the salt, then you hash the password, then you combine two hashes.

Even the size of your output string is different.
It's hard to explain without showing you the actual hashes though. Write a script to echo each one and you'll see it more clearly.

This post has been edited by Cbeppe: 23 April 2012 - 03:31 PM

Was This Post Helpful? 1
  • +
  • -

#8 Cynosure  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 44
  • Joined: 04-February 09

Re: PHP Login Script - hashed & salted password not matching

Posted 23 April 2012 - 03:35 PM

Ahhhh! That helped a lot. Thank you so much!

I've got to head out for a bit; when I return I will post my script to compare the values and hopefully post a corrected version of the code.

Thank you both! =)
Was This Post Helpful? 0
  • +
  • -

#9 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3554
  • View blog
  • Posts: 10,335
  • Joined: 08-June 10

Re: PHP Login Script - hashed & salted password not matching

Posted 23 April 2012 - 03:58 PM

View Postcreativecoding, on 24 April 2012 - 12:04 AM, said:

I don't see why you would even store your salt inside of a database. I mean, the whole reason for a salt is so that if your database is compromised, it would make it almost impossible to use something like rainbow tables and figure out the password.

and a salt inside a database still does that. but its main effect is that each user has a different salt so that, if a password is used twice (even by coincidence), the hash thereof is different. and you have to crack the password hash of each user separately (which takes even more time than all passwords with a single hash each).
Was This Post Helpful? 3
  • +
  • -

#10 Cynosure  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 44
  • Joined: 04-February 09

Re: PHP Login Script - hashed & salted password not matching

Posted 23 April 2012 - 04:12 PM

Okay.. so I have created a script and can see that they are very, very different. I'm not sure what I did wrong during my first attempt to create this script.

I'm now trying to figure out how to get the two statements to be equal.
Was This Post Helpful? 0
  • +
  • -

#11 Cbeppe  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 31
  • View blog
  • Posts: 215
  • Joined: 16-September 09

Re: PHP Login Script - hashed & salted password not matching

Posted 23 April 2012 - 05:11 PM

You're not doing anything wrong, you're just not using the same expression in both scripts. My suggestion would be to use the following in both scripts:

$password    = $_POST['theUsersPass'];
$salt        = md5($_POST['username'].$_POST['emailAddress']);
$pepper      = "72gGeeLjuZfGa/#$fCilQpPmcVKkA8r7";

$hash = hash('sha256', $salt.$password.$pepper);



This adds some more levels of security as well. Firstly, the password is what the user chooses as their password.
Secondly, we generate the salt by creating an MD5 hash of the user's username and email address (for example). This avoids storing it in the database (although what Dormilich said is completely true).
Thirdly, and a new feature, is the "pepper". This is a value that is stored in the code itself so that nobody except you would ever get a hold of it. In combination with your salt, this should make it nearly impossible to crack your stored hashes should someone ever gain access to your DB. Whether you want to actually use it is up to you, but I don't see a reason why not.

Your hash is now being generated by first adding the salt, then the password, then the pepper. The hash function will then produce a SHA256 hash of this new string.

Hope this clears things up.
Was This Post Helpful? 1
  • +
  • -

#12 Cynosure  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 44
  • Joined: 04-February 09

Re: PHP Login Script - hashed & salted password not matching

Posted 23 April 2012 - 05:20 PM

I've been trying very hard to get the same expression in both scripts. I did some research on hashing/salting on the web which made the process make a bit more sense. I tried rewriting the login script about 20 times to get it to match the value of the register script and each string was entirely different. Haha. I realized what I was trying to do was "de-hash" and "de-salt" the database values to get the original which apparently isn't possible.

I found some other hashing and salting tutorials so I'm going to try each of them until one clicks in me and works.

Your code and explanation are very good! You've been extremely helpful. I will also try implementing yours and see if I can't get it to work. I don't have a section for user e-mail addresses, but I know I can use any values there. Is there a benefit to using random salt values as opposed values in my tables?
Was This Post Helpful? 0
  • +
  • -

#13 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6078
  • View blog
  • Posts: 23,548
  • Joined: 23-August 08

Re: PHP Login Script - hashed & salted password not matching

Posted 23 April 2012 - 05:38 PM

This is what you use to build a secure login system in PHP.
Was This Post Helpful? 2
  • +
  • -

#14 no2pencil  Icon User is offline

  • Admiral Fancy Pants
  • member icon

Reputation: 5364
  • View blog
  • Posts: 27,325
  • Joined: 10-May 07

Re: PHP Login Script - hashed & salted password not matching

Posted 23 April 2012 - 05:40 PM

View PostJackOfAllTrades, on 23 April 2012 - 08:38 PM, said:

This is what you use to build a secure login system in PHP.

That's an awesome link. The first sentence is perfect (& quorate) for the age old & often duplicated debit of hashing vs encryption.
Was This Post Helpful? 1
  • +
  • -

#15 Cbeppe  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 31
  • View blog
  • Posts: 215
  • Joined: 16-September 09

Re: PHP Login Script - hashed & salted password not matching

Posted 23 April 2012 - 05:45 PM

Quote

I realized what I was trying to do was "de-hash" and "de-salt" the database values to get the original which apparently isn't possible.

That's not the way to go. Instead, hash the password when the user registers and save it in the DB. Then when he tries to log in, hash the password that he submits using THE SAME method. Then you query the database for the hashed value for the password and see if they match. If they do, he logs in, else, display an error message.

Quote

I found some other hashing and salting tutorials so I'm going to try each of them until one clicks in me and works.

What I said above is really all there is to it. At least for basic uses.

Quote

I don't have a section for user e-mail addresses

You don't need that. All you need is something that is unique to the user that you can make into a salt. Infact, it might be better to just use the md5($_POST['username']). That way it's easily generated when the user tries to log in.

Quote

Is there a benefit to using random salt values as opposed values in my tables?

The salt value isn't random. It's unique to each user, which is the main purpose of it. The "pepper" is a random value that I added to the end of the string to make it longer and to add complexity (meaning more types of characters).

Here is the gist of how your scripts should work:
/** REGISTER.PHP **/

<?php

$username    = $_POST['username'];
$password    = $_POST['pass'];
$salt        = md5($username);
$pepper      = "72gGeeLjuZfGa/#$fCilQpPmcVKkA8r7";

$hash = hash('sha256', $salt.$password.$pepper);

mysql_query("
    INSERT INTO users (username, password) 
    VALUES ('$username','$password')
") or die(mysql_error());
?>



/** LOGIN.PHP **/

<?php

$username    = $_POST['username'];
$password    = $_POST['pass'];
$salt        = md5($username);
$pepper      = "72gGeeLjuZfGa/#$fCilQpPmcVKkA8r7";

$hash = hash('sha256', $salt.$password.$pepper);

$q    = mysql_query("
            SELECT password
            FROM users
            WHERE username = '$username'
        ") or die(mysqli_error());

if ($res  = mysql_fetch_assoc($q)) {
    if ($res['password'] == $hash) {
        // Log In user here
    } else {
        // Wrong username or password
    }
} else {
    // User does not exist in database
}
?>



I'm not guaranteeing for that code as it's 02:45 AM, but it should give you the general idea.

Cbeppe.

EDIT: Or use the link that JackOfAllTrades posted while I was typing this :D

This post has been edited by Cbeppe: 23 April 2012 - 05:48 PM

Was This Post Helpful? 2
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2