PHP ログインを作成中ですが、SHA1 または Md5、あるいは別の StackOverflow の記事で読んだ SHA256 のどれを使用するか決めようとしています。どれが他のものよりも安全でしょうか? SHA1/256 の場合、ソルトはやはり使用すべきでしょうか?
また、これはパスワードをハッシュとして MySQL に保存する安全な方法でしょうか?
function createSalt()
{
$string = md5(uniqid(rand(), true));
return substr($string, 0, 3);
}
$salt = createSalt();
$hash = sha1($salt . $hash);
ベストアンサー1
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.
Using bcrypt in PHP 5.5+
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.
Two caveats of bcrypt
- Bcrypt will silently truncate any password longer than 72 characters.
- Bcrypt will truncate after any
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) offersBcryptSha
PasswordLock
is similar toBcryptSha
but it also encrypts the bcrypt hashes with an authenticated encryption library.
TL;DR - Use bcrypt.