哈希密码注册/登录

时间:2014-03-03 20:06:24

标签: php salt sha256

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

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

所以我抓住了数据:

$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_pa​​ss |盐

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

首先基于用户(电子邮件),我抓住encrypted_pa​​ss和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 and hash SHA256 for login password

任何评论都表示赞赏!谢谢!

3 个答案:

答案 0 :(得分:3)

在向哈希添加salt时,唯一可以防止使用的是使用名为“Rainbow Tables”的预先计算的哈希表。这些在很长一段时间内都不是主要问题,但是因为:

  1. 包含扩展字符集的彩虹表大量,有些需要超过16GB的RAM才能搜索。
  2. 跨多台计算机的并行化暴力破解,或卸载到AWS等云服务更快,更便宜,并且使得添加简单的盐几乎无关紧要。
  3. 更好的算法将密码散列数千次,并以加密的“正确”方式应用给定的盐,使其更难破解。但是,它们基于SHA和MD5的哈希算法设计得小而快,并且强制它们需要大量的CPU时间,这样便宜且易于并行化。

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

    TL; DR Hashing比明文更好,盐腌比没有盐水更好,bcrypt比其他所有东西都要好几英里所以 frickin使用它

答案 1 :(得分:1)

您应该使用内置的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";

答案 2 :(得分:1)

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

当然,了解盐是如何工作的(以及正确处理它的难度)是很好的,所以试试看,但是使用上面的功能为你的生命系统。