Password hashing problem

Hi guys,

I seem to be having an issue using password hashing, ive never used it before and think im missing something obvious but cant see for looking…

Basically, i add a user from a php form that is then written to mysql database, the user gets added fine with a nonsense looking password. But when i try and log in with that user i re hash the password as i think im supposed to but i seem to get a different hash.

example code.
Add User form posts to this php script:

		# generate a random salt to use for this account
		$salt = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
		$saltedPW =  $_POST['password'] . $salt;

		$hashedPW = hash('sha256', $saltedPW);
		$query = "INSERT INTO users (username, password, access, salt) VALUES('" . $_POST['username'] . "','" . $hashedPW . "','" . $_POST['access'] . "','" . $salt . "') ";
		$result = mysql_query($query) or die(mysql_error());
		if ($query) {
			echo $_POST['username']." Successfully Added.";

Login form posts to this:

	$saltQuery = "SELECT salt FROM users WHERE username = '" . $_POST['username'] . "' ";
	$result = mysql_query($saltQuery);
	$row = mysql_fetch_assoc($result);
	$salt = $row['salt'];

	$saltedPW =  $_POST['password'] . $salt;
	$hashedPW = hash('sha256', $saltedPW);

    $query = "SELECT * FROM users WHERE username = '" . $_POST['username'] . "' AND password = '". $hashedPW ."' ";
	$result = mysql_query($query) or die(mysql_error());
	$row = mysql_fetch_row($result); // get the single row.
	$access = $row[3]; // display the value.
	if(mysql_num_rows($result) > 0) {
   stuff here

Any suggestions where im going wrong?

Try echoing salt before entering it into the db and then also echoing after retrieving it and ensure they are the same. I have a feeling you salt is being truncated in your db.

Hi Kyle,

Appreciate the quick response. As always you were spot on. I have stared at the code for so long now that i hadn’t noticed the salt was being truncated.

Thanks again.

Definitely not! lol. I’d recommend just running a substr() on your entry to the db to whatever your field size is in case bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM)) has a variable output length and may exceed your column size again.

Well you’ve certainly helped me out in the past. That seems like a good suggestion i will add it as soon as possible…