Search code examples
phpencryptioncrypt

PHP crypt salt generation


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?


Solution

  • 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