1

I am generating salt for php crypt function like this

$hashSalt = substr(md5(time().uniqid(rand())),0, 22);

$hashedPassword = crypt('SmithJohn', '$2a$07$'.$hashSalt.'$');

From my understanding this is a good method. What are your thoughts?

phantomCoder
  • 1,281
  • 2
  • 15
  • 30
  • possible duplicate of [Secure random number generation in PHP](http://stackoverflow.com/questions/1182584/secure-random-number-generation-in-php) – deceze Jul 24 '13 at 17:17

1 Answers1

2

Too complicated and not necessarily random enough. Use sources that are made for that purpose:

mcrypt_create_iv($salt_len, MCRYPT_DEV_URANDOM)

or

openssl_random_pseudo_bytes($salt_len)

or

$buffer = '';
$f = fopen('/dev/urandom', 'r');
$read = strlen($buffer);
while ($read < $salt_len) {
    $buffer .= fread($f, $salt_len - $read);
    $read = strlen($buffer);
}
fclose($f);

Preferably all used as several layers of fallback, as shown in https://github.com/ircmaxell/password_compat/blob/master/lib/password.php#L84

Maarten Bodewes
  • 84,836
  • 13
  • 136
  • 244
deceze
  • 491,798
  • 79
  • 706
  • 853
  • Why we need fopen here? – phantomCoder Jul 24 '13 at 15:40
  • 1
    [This answer](http://stackoverflow.com/questions/1182584/secure-random-number-generation-in-php/1551064#1551064) has more details about secure random number generation in PHP. – ntoskrnl Jul 24 '13 at 15:48
  • 1
    @phpsessionid Because it's a fallback method to read from `/dev/urandom`. If you don't know what that is, see http://en.wikipedia.org/wiki//dev/urandom. – deceze Jul 24 '13 at 15:49