-1

It's the first time I am using PHP native password functions in my application. I stored user's password using code below:

password_hash($this->input->post('password'),PASSWORD_BCRYPT);

And result is stored in database. Now I want to verify user in login process.

My question is here. I have 2 choices:

Method 1

$sql = "SELECT id,password FROM tbl_members WHERE email = ? LIMIT 1";
$result = $this->db->query($sql,array('user@site.com'));
if ($result->num_rows()) {
   $row = $result->row();
   $hash = $row->password;
   if (password_verify($this->input->post('password'), $hash)) echo 'Successful login';
}

Method 2

$hash = password_hash($this->input->post('password'),PASSWORD_BCRYPT);
$sql = "SELECT id FROM tbl_members WHERE email = ? AND password = ? LIMIT 1";
$result = $this->db->query($sql,array('user@site.com',$user_hashed_password));
if ($result->num_rows()) echo 'Successful Login';

Which method is more suitable for a login process?

Mohammad Saberi
  • 12,864
  • 27
  • 75
  • 127
  • One is vulnerable to timing attacks the other is not. The API is provided for a reason. Use it. – PeeHaa Sep 14 '16 at 07:46
  • 1
    @PeeHaa Actually… one *works*, and the other does not… – deceze Sep 14 '16 at 07:47
  • password_hash is more secured for me, – Beginner Sep 14 '16 at 07:47
  • @deceze good call. Didn't even see the random salt :) Just read the last sentence – PeeHaa Sep 14 '16 at 07:47
  • 1
    *"Both of them work well"* – Really? The second method should absolutely *not* work. – deceze Sep 14 '16 at 07:53
  • @deceze you are right. It was my mistake. But could you tell me why the method 2 does not return the same hashed value as `password_hash($this->input->post('password'),PASSWORD_BCRYPT);` result? – Mohammad Saberi Sep 14 '16 at 07:57
  • 1
    Because the salt is random unless you explicitly set it, but that functionality is deprecated as of PHP7, so just stick with option 1. – Jonnix Sep 14 '16 at 08:00
  • @PeeHaa the tag I was created it can be a keyword to find such questions. I don't create a tag regularly as you think. I think it was an important keyword (tag) for this question like `php-password-hash` – Mohammad Saberi Sep 14 '16 at 08:00
  • 1
    Because `password_hash` adds a *random salt*. See http://security.stackexchange.com/a/31846/719 – deceze Sep 14 '16 at 08:00

1 Answers1

-1

The first method is the best, and is as it should be used. The encryption, the salt etc are stored in the hash string, so if you change your encryption, the old stored hashes are still valid, and more, you don't need to store salt and algorithm, just the hash.

Al Foиce ѫ
  • 4,195
  • 12
  • 39
  • 49