Correctly using crypt() with SHA512 in PHP

The main reason to run the algorithm for a certain amount of rounds is simply to slow it down to make brute forcing attacks uninteresting. For that 5000 iterations are enough even for modern hardware. You could as well use 100000 but then your server admin would probably want to have a word with you :-) rounds=5000 is the default for SHA-512. The minimum is 1000 and the maximum very high.


Use OpenSSL for salt generation, it's even more random. And maybe 20000 rounds to future proof your code a bit.

function cryptPassword($password, $salt = "", $rounds = 20000)
{
    if ($salt == "")
    {
        // Generate random salt
        $salt = substr(bin2hex(openssl_random_pseudo_bytes(16)),0,16);
    }
    // $6$ specifies SHA512
    $hash = crypt($password, sprintf('$6$rounds=%d$%s$', $rounds, $salt));

    return $hash;
}