1

I am using bcrypt() function for storing my password of a user. Now if a user wants to change his/her password, then he/she will put his old password and I will check that with old password.

Problem is whenever I am using bcrypt function to the user inputed password it shows some new generated password.

Ex: During registration a user registered with 111111 password. And during change password the user also inputing 111111 but the both comes different.

Q: Why it shows different. I am using this in laravel 5.4.

Saroj
  • 1,343
  • 4
  • 15
  • 31
  • Possible Solution : https://stackoverflow.com/questions/4795385/how-do-you-use-bcrypt-for-hashing-passwords-in-php – Naincy May 24 '17 at 08:41
  • With BCrypt/password_* API, the whole idea is that you *hash* it - it will be a different string each time, which is why you need to use functions like `password_verify()` to verify the password, and not compare it against a re-hashed string (like you do when checking passwords that are `sha1()`, `md5()` etc which isn't secure). – Qirel May 24 '17 at 08:43
  • Possible duplicate of [Secure hash and salt for PHP passwords](https://stackoverflow.com/questions/401656/secure-hash-and-salt-for-php-passwords) – Dymen1 May 24 '17 at 08:48
  • Thanks @Qirel for giving the brief idea. – Saroj May 24 '17 at 09:12

1 Answers1

1

You can use Hash::check() to check the old password against the one you have in your database as such

if (Hash::check($oldPassword, $passwordFromDb)) 
{
   // it is a match
}

As such, an example implementation would be:

$oldPassword    = $request->input('old-password');
$newPassword    = $request->input('new-password');
$hashedPassword = Auth::user()->password;

if (Hash::check($oldPassword, $hashedPassword)) 
{
    $user = User::find(Auth::user()->id)
                ->update(
                    ['password'=> Hash::make($newPassword)]
                );
}
Mozammil
  • 8,520
  • 15
  • 29
  • Thnaks for your time. But why did you use input, when you can get the all information in $request object. Like -> $request->old-password. – Saroj May 24 '17 at 09:15
  • I like to keep it consistent across my application. See [doc](https://laravel.com/docs/5.4/requests#retrieving-input) – Mozammil May 24 '17 at 10:50