验证 SHA512 密码 if($row['password']==hash('SHA512', $upass))

Verify a SHA512 password if($row['password']==hash('SHA512', $upass))

当用户在我的网站上创建帐户时,他们的密码将使用 SHA512 存储。我的问题是当用户尝试使用他们的密码登录时,我相信我验证密码不正确但是我看不出我做错了什么。

这是我的有效注册脚本:

 $uname = mysql_real_escape_string($_POST['uname']);
 $sname = mysql_real_escape_string($_POST['sname']);
 $email = mysql_real_escape_string($_POST['email']);
 $upass = mysql_real_escape_string($_POST['pass']);

 $upass = hash('SHA512', $upass);

密码'Test'在数据库中存储为:

ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f88

这是我的登录脚本:

if($row['password']==hash('SHA512', $upass))
 {
  $_SESSION['user'] = $row['user_id'];
  header("Location: account.php");

如果有人可以编辑我的登录代码,以便它可以检索和验证 SHA512 字符串,那么将不胜感激。

我不担心完全改变我的登录系统以使其更安全,这是一个非常简单的系统,仅用于存储用户对网站的偏好,请问我们是否厌倦了使用 SHA512。

由于上面已经计算了hash,相比之下就不需要再调用hash函数了:

if($row['password']==$upass)

而不是:

if($row['password']==hash('SHA512', $upass))

Here is the hash_equals() for php version >= 5.6.0 If you are using lower version then you can use code from below.

if(!function_exists('hash_equals')) {
  function hash_equals($str1, $str2) {
    if(strlen($str1) != strlen($str2)) {
      return false;
    } else {
      $res = $str1 ^ $str2;
      $ret = 0;
      for($i = strlen($res) - 1; $i >= 0; $i--) $ret |= ord($res[$i]);
      return !$ret;
    }
  }
}

Matching hash.

$expected  = crypt('Test', 'a$addsomecustomstring$');
$correct   = crypt('Test', 'a$addsomecustomstring$');
$wrong = crypt('tets',  'a$addsomecustomstring$');

var_dump(hash_equals($expected, $correct)); //true
var_dump(hash_equals($expected, $wrong)); //false