I'm making a php login, and I'm trying to decide whether to use SHA1 or Md5, or SHA256 which I read about in another stackoverflow article. Are any of them more secure than others? For SHA1/256, do I still use a salt?
Also, is this a secure way to store the password as a hash in mysql?
function createSalt()
{
$string = md5(uniqid(rand(), true));
return substr($string, 0, 3);
}
$salt = createSalt();
$hash = sha1($salt . $hash);
Neither. You should use bcrypt
. The hashes you mention are all optimized to be quick and easy on hardware, and so cracking them share the same qualities. If you have no other choice, at least be sure to use a long salt and re-hash multiple times.
PHP 5.5 offers new functions for password hashing. This is the recommend approach for password storage in modern web applications.
// Creating a hash
$hash = password_hash($password, PASSWORD_DEFAULT, ['cost' => 12]);
// If you omit the ['cost' => 12] part, it will default to 10
// Verifying the password against the stored hash
if (password_verify($password, $hash)) {
// Success! Log the user in here.
}
If you're using an older version of PHP you really should upgrade, but until you do you can use password_compat to expose this API.
Also, please let password_hash()
generate the salt for you. It uses a CSPRNG.
NUL
characters.(Proof of Concept for both caveats here.)
You might be tempted to resolve the first caveat by pre-hashing your passwords before running them through bcrypt, but doing so can cause your application to run headfirst into the second.
Instead of writing your own scheme, use an existing library written and/or evaluated by security experts.
Zend\Crypt
(part of Zend Framework) offers BcryptSha
PasswordLock
is similar to BcryptSha
but it also encrypts the bcrypt hashes with an authenticated encryption library.TL;DR - Use bcrypt.