views:

188

answers:

1

Hello

I'm trying to build a safe user authentication system.

The code is from http://net.tutsplus.com/tutorials/php/simple-techniques-to-lock-down-your-website/

But Im trying to change from md5 to sha-256, But It wont login.

I just changed from

$auth_pass = md5( $row['salt'] . $password . $stat_salt );

to

$auth_pass = hash('sha256', $row['salt'] . $password . $stat_salt );

It does insert to db correctly but the login part wont work for some reason. Works with md5 but not sha256. Do u have to use sha256 in a diffrent way?

Registration:

// generate a unique salt
$salt = uniqid(mt_rand());

// combine them all together and hash them
$hash = hash('sha256', $salt . $password . $stat_salt );

// insert the values into the database
$register_query = mysql_query("INSERT INTO users (username, password, salt) VALUES ('".$username."', '".$hash."', '".$salt."')") or die("MySQL Error: ".mysql_error());

Login

// grab the row associated with the username from the form
$grab_row = mysql_query("SELECT * FROM users WHERE username = '".$username."'") or die ("MySQL Error: ".mysql_error());

// if only one row was retrieved
if (mysql_num_rows($grab_row) == 1) {

// create an array from the row fields
$row = mysql_fetch_array($grab_row);

// re-hash the combined variables
$auth_pass = hash('sha256', $row['salt'] . $password . $stat_salt );

// check the database again for the row associated with the username and the rehashed password
$checklogin = mysql_query("SELECT * FROM users WHERE username = '".$username."' AND password = '".$auth_pass."'") or die("MySQL Error: ".mysql_error());

// if only one row is retrieved output success or failure to the user
if (mysql_num_rows($checklogin) == 1) {
echo "<h1>Yippie, we are authenticated!</h1>";
} else {
echo '<h1>Oh no, we are not authenticated!</h1>';
}
} else {
echo '<h1>Oh no, we are not in the database!</h1>';
}
}
+4  A: 

It does insert to db correctly but [...]

how do you test it? md5 returns 32-digit string, hash('sha256', ...) return 64-digit string. Is your password field long enough to accommodate it? if it's not, on insert $hash will be clipped to the length of the field, and comparison on select will fail.

SilentGhost
Even if it were not, shouldn't the clipped SHA result be the same?
fbrereto
what clipped sha results have to do with it? OP's comparing `varchar`s
SilentGhost
that was the problem my password field was 32 varcharthank you so muich!
Włodzimierz
+1 for psychic debugging! :)
Kip