Martin
Martin

Reputation: 4846

php password checking

I have a small web app that uses a simple username/password login scheme. I've noticed several times it won't allow a user to login when they correctly input the password.

The code originally was just encrypting the user's typed in password on initial registration as:

function encode5t($str) {
  for($i=0; $i<5;$i++)   {
     $str=strrev(base64_encode($str)); //apply base64 first and then reverse the string
  }
  return $str;
 }

 $password=mysql_real_escape_string($_POST['password']);
 $pass=encode5t($password);

and then $pass is inserted into a MySQL database. Then the same function is used to encrypt the password on login and is checked against the database like so:

$username = $_POST['username'];
$psw = $_POST['password'];
$npsw=encode5t($psw);

$query = sprintf("SELECT * FROM members WHERE username='%s' AND password='%s'",
    mysql_real_escape_string($username),
    mysql_real_escape_string($npsw));

The problem arises depending on how the password is input into the form. If it's simply typed in, there is no problem, but if the password is copied/pasted into the form (as from an email containing a newly generated password), it fails. The encryption function creates and entirely different hash and doesn't match, so the user isn't logged in.

I've played with the encoding and changed it to a just use md5() but I get the same end result - a cut/paste results in a different hash than what simply typing the password into the form results in.

Is there something in the page encoding that would make a copy/paste text different from a typed one?

Upvotes: 0

Views: 506

Answers (1)

Brad
Brad

Reputation: 163612

The problem is that when users paste in a username/password, it often has spaces before or after it. Run those fields through trim() to fix this.

On another note, what you have isn't all that secure. Your base64 string won't fool anybody for long, and md5 should not be used for password hashes, especially when not salted. Try something a bit more robust, such as whirlpool. Finally, I suggest using prepared queries with PDO to avoid injection issues. You are escaping your data currently... that's great! But, it is best not to take a chance with missing an escape somewhere.

Upvotes: 3

Related Questions