哈希密码注册/登录



我在谷歌上搜索了正确的方法,但在如何做到这一点上有很多变化。所以我想出了这个主意,不介意一些批评和更好实践的链接。

//注册表格-用户提供用户名(电子邮件)密码(文本)//

所以我获取了数据:

$user = mysql_real_escape_string($_POST['user']);
$pswd = mysql_real_escape_string($_POST['pass']);
$salt = hash( 'sha256', microtime() . rand() );
$encrypt = hash( 'sha256', $pswd . $salt );

然后插入数据库user_email | encrypted_pass | salt

//登录表单-用户提供用户名(电子邮件)密码(文本)//

因此,首先基于用户(电子邮件),我获取encrypted_pass和salt信息。然后,

$user = mysql_real_escape_string($_POST['user']);
$pswd = mysql_real_escape_string($_POST['pass']);
$encrypted_pass_fromDB = $var['encrypted_pass'];
$salt_fromDB = $var['salt'];
if (hash( 'sha256', $passwrd . $salt_fromDB) === $encrypted_pass_fromDB)
{
echo "GOT IT!";
}

我读过bcrypt是一个更好的选择,但现在我想更好地理解SALT方法。此外,当我使用$options=['cost'=>11,]时;我得到一个错误分析错误:语法错误,意外的"[">,但我想这是一个单独的问题。使用了基于PHP salt和哈希SHA256的代码作为登录密码

欢迎发表评论!谢谢

在哈希中添加salt时,唯一可以防止的是使用称为"Rainbow tables"的预计算哈希的巨大表。在相当长的一段时间内,这些都不是一个主要问题,尽管是因为:

  1. 包含扩展字符集的Rainbow表是大型,有些表需要16GB以上的RAM才能进行搜索
  2. 跨多台计算机的并行预处理破解,或卸载到AWS等云服务,速度更快、更便宜,而且添加简单的盐几乎无关紧要

更好的算法将密码散列数千次,并以加密的"正确"方式应用给定的salt,使其更难破解。然而,它们所基于的哈希算法,如SHA和MD5,被设计得又小又快,并且对它们进行预处理需要大量的CPU时间,这既便宜又易于并行化。

Bcrypt不同。它使用Blowfish算法,该算法需要相对大量的RAM,这是昂贵的,因此很难并行化。这就是为什么每个人都强烈推荐它。

TL;DR哈希比明文好,加盐比无盐好,bcrypt比几乎所有其他东西都好,所以frickin使用它

您应该使用内置的crypt函数:

http://php.net/crypt

你有两个选择:

让PHP Crypt生成盐

$user = mysql_real_escape_string($_POST['user']);
$pswd = mysql_real_escape_string($_POST['pass']);
//Salt is generated automatically
$encrypt = crypt( $pswd );

自己生成盐

$user = mysql_real_escape_string($_POST['user']);
$pswd = mysql_real_escape_string($_POST['pass']);
//These are the settings for the salt (Separated so you can understand it)
$algorithm = "2a";
$length = "12";
//Start the salt by specifying the algorithm and length
$salt = "$" . $algorithm . "$" . $length . "$";
//Add on random salt and make base64 adjusted for bcrypt's version
$salt .= substr( str_replace( "+", ".", base64_encode( mcrypt_create_iv( 128, MCRYPT_DEV_URANDOM ) ) ), 0, 22 );
//Encrypt with your generated salt
$encrypt = crypt( $pswd, $salt );

验证它很容易:

if ( $encrypted_pass_fromDB_with_salt === crypt( $passwrd, $encrypted_pass_fromDB_with_salt ) ) echo "ok";

PHP现在提供了一种生成安全密码哈希的简单方法,我们应该使用它,看看函数password_hash()。

// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT);
// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($password, $existingHashFromDb);

当然,了解盐是如何工作的(以及正确处理它有多难)是很好的,所以尝试一下,但要在你的生活系统中使用上面的功能。