SHA1 与 md5 与 SHA256:哪个用于 PHP 登录? [英] SHA1 vs md5 vs SHA256: which to use for a PHP login?

查看:38
本文介绍了SHA1 与 md5 与 SHA256:哪个用于 PHP 登录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 php 登录,我正在尝试决定是使用 SHA1 还是 Md5,或者我在另一篇 stackoverflow 文章中读到的 SHA256.它们中的任何一个比其他的更安全吗?对于 SHA1/256,我还使用盐吗?

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?

另外,这是一种将密码作为哈希存储在 mysql 中的安全方法吗?

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);

推荐答案

两者都不是.你应该使用 bcrypt.您提到的哈希都经过优化,可以在硬件上快速简便,因此破解它们具有相同的品质.如果你别无选择,至少一定要使用长盐并多次重新哈希.

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 提供了新的密码散列函数.这是现代 Web 应用程序中推荐的密码存储方法.

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.
}

如果您使用的是旧版本的 PHP 您确实应该升级,但在您升级之前您可以使用 password_compat 来公开此 API.

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.

另外,请让 password_hash() 为您生成盐.它使用 CSPRNG.

  1. Bcrypt 会以静默方式截断任何超过 72 个字符的密码.
  2. Bcrypt 将在任何 NUL 字符后截断.
  1. Bcrypt will silently truncate any password longer than 72 characters.
  2. Bcrypt will truncate after any NUL characters.

(概念证明,此处有两个警告.)

(Proof of Concept for both caveats here.)

您可能想通过 在通过 bcrypt 运行密码之前预先对密码进行哈希处理,但这样做可能会导致您的应用程序先行进入第二个.

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.

  • ZendCrypt (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 - 使用 bcrypt.

这篇关于SHA1 与 md5 与 SHA256:哪个用于 PHP 登录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆