Click to See Complete Forum and Search --> : SHA function - compare password doesn't work


sjcoder07
March 14th, 2008, 03:03 AM
Hello everyone:

I am doing a exercise to compare user entry (password) with existing password saved in the database.

a)I used SHA() function to encrypt the password in insert command.
b) I also used SHA() in select clause to encrypt user entry password

I alwasy got an error message saying that wrong user password entered.

Please check my code and give me some suggestion on how to resolve this problem. Thanks!

table holds user_id and user_password two entry

create table tbl_auth_user(

user_id varchar(10) NOT NULL,
user_password char(32) NOT NULL,

primary key (user_id)
);

insert into tbl_auth_user (user_id, user_password) VALUES ('theadmin', SHA('1234'));

PHP code:

<?php
$errorMessage = '';
$db_name = 'pc_inventory';

if(isset($_POST['userid']) && isset($_POST['txt_password']) )
{
//connect to database
$db_connect = mysql_connect('', 'root', '');

if($db_connect)
echo "you connected to the dabase<br />";
else
die ('connection to db failed' . mysql_error());


//select database
$db_selection = mysql_select_db($db_name);
if($db_selection)
echo "$db_name being selected.<br />";
else
die("$db_name not selected" . mysql_error());


$userId = $_POST['userid'];
$password = $_POST['txt_password'];

echo "$userId / $password.<br />";

// check if the user id and password combination exist in database
$sql = "SELECT user_id
FROM tbl_auth_user
WHERE user_id = '$userId' AND user_password = SHA('$password')";

$result = mysql_query($sql) or die('Query failed. ' . mysql_error());

if(mysql_num_rows($result) == 1)
{
echo "user name and password exist in the database<br />";
}
else
{
$errorMessage = 'Sorry, wrong user id / password';
}

}
?>

<html>
<title>
Password Funtion
</title>

<body>

<?php
if ($errorMessage != '') {
?>

<p align="center"><b><font color="#990000"><?php echo $errorMessage; ?></font></b></p>
<?php
}
?>

<form name="" id="" action="" method="post">
User ID:<input type="text" name="userid" id="userid" value="" /><br /><br />
Password:<input type="password" name="txt_password" id="txt_password"><br /><br />
<input type="submit" name="submit" value="Submit" />


</form>

</body>
</html>

PeejAvery
March 14th, 2008, 08:54 AM
SHA1 returns 40 characters, but you have only allowed 32 characters for the password column. MD5 returns 32.

Nibinaear
March 15th, 2008, 11:01 AM
I've never personally used SHA1 and don't know how secure it is, but you might want to try this also:


$mypass="computer";
define('SALT','cheese');
$hashpass=md5(SALT.$mypass.SALT);


This way you properly salt the password. Of course don't tell anyone your salt and keep it in outside the root directory where only php can find it.