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,499
  • 3
  • 18
  • 32
  • 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
  • 90,524
  • 13
  • 150
  • 263
deceze
  • 510,633
  • 85
  • 743
  • 889
  • 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