-4

we are using Laravel Framework 5.7.15 with PHP version: 7.2.14-1 and we use below code to generate temporary password then hash it in the database. In around 80 times all passwords hash matched the string however there were around 3 not matched strings , I searched for a cause and nothing appeared...

$input['tmp_password'] = substr(str_shuffle("0123456789"), 0, 4); // Random four digits
$input['password'] = Hash::make($input['tmp_password']);
Salman Zafar
  • 3,844
  • 5
  • 20
  • 43
  • 1
    That is a really bad way to generate a random password. Why not do something like this https://stackoverflow.com/questions/6101956/generating-a-random-password-in-php. Even the PHP help page for `str_shuffle` warns you not to use this function for things that need to be secure. – jfadich Sep 10 '19 at 21:15
  • Can you please explain a bit more? You posted two lines of code. – dparoli Sep 10 '19 at 21:17
  • What do you mean by "not matched"? Are you saying `Hash::check` if failing on the generated hashes? That's extraordinarily unlikely. – ceejayoz Sep 10 '19 at 21:26
  • We are using this method because we want a simple random password , and yes hash check and this is why this is so weird – Abdallah Ibrahim Sep 10 '19 at 21:56

2 Answers2

1

As stated in the comments there are better ways to generate random passwords other than using str_shuffle. Using this method the passwords generated will always contain the same given chars just in a different order, making it easy to guess.

One example of a better way is using the helper method random from Str class

use Illuminate\Support\Str;

$password = Hash::make(Str::random(40)); // 40 being the number of chars generated
Helder Lucas
  • 3,273
  • 2
  • 21
  • 26
1

In ten thousand iterations of your code, I was unable to cause a single hash to fail.

$input = [];

for($i = 0; $i < 10000; $i++) {
    $input['tmp_password'] = substr(str_shuffle("0123456789"), 0, 4);
    $input['password'] = Hash::make($input['tmp_password']);

    if(!Hash::check($input['tmp_password'], $input['password'])) {
        print "OH SHIT\n";
    }
}

Something else is going wrong, in code you haven't shown. As you indicate in the comments, you're doing some other stuff with $user somewhere that's not in your code sample at all.

ceejayoz
  • 176,543
  • 40
  • 303
  • 368