Before inserting data to the database, I encrypted the user name and password like this:
$userName=strip_tags($userName);
$pass=strip_tags($pass);
$userName= htmlentities($userName, ENT_QUOTES, 'UTF-8');
$pass= htmlentities($pass, ENT_QUOTES, 'UTF-8');
$userName=mysql_real_escape_string($userName);
$pass=mysql_real_escape_string($pass);
$salt = 'SHIFLETT';
$password_hash = md5($salt . md5($pass.$salt));
This was done to prevent SQL attacks and general SQL injections.
Now I want to check the pass and name the user gives me when logging in. I repeated the same process of escaping character stripping, and escaping special characters.
So here is my function to check the pass:
function validateLogin($user_name, $pass)
{
$userName=strip_tags($userName);
$pass=strip_tags($pass);
$userName= htmlentities($userName, ENT_QUOTES, 'UTF-8');
$pass= htmlentities($pass, ENT_QUOTES, 'UTF-8');
$userName=mysql_real_escape_string($userName);
$pass=mysql_real_escape_string($pass);
$salt = 'SHIFLETT';
$password_hash = md5($salt . md5($pass.$salt));
$result=mysql_query("SELECT COUNT(*) AS Result FROM users WHERE user_name='$user_name' AND pass='$password_hash'");
mysql_close();
if($row=mysql_fetch_array($result))
{
if($row['Result']>0)
{
echo "Login successful";
}
else
{
echo "Login unsuccessful";
}
}
}
My question is with all those security precautions, will validation work? will MD5 return the same pass if I used the same MD5 encoding on the insert and then on the select statement?
For flexibility, you should make a function to hash (not encrypt) your password. Also, use a stronger algorithm than md5 (like sha512 used in my example).
I also recommend using
mysql_real_escape_string.And use an auto_incremented int instead and select it.
Then simply compare the returned row with the username and password.
To answer your question: yes, comparing a hashed password with a hashed string in the database will work.