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

半世苍凉 提交于 2020-01-07 09:09:08

问题


When a user creates a account on my website then their password is stored using SHA512. My problem is when the user tries to login with their password, i believe i am verifying the password incorrectly however i cannot see what i have done wrong.

Here is my register script which works :

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

The password 'Test' is stored in the database as:

ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f88

Here is my login script:

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

If any body could please edit my login code so that it can retrieve and verify the SHA512 string then it would be greatly appreciated.

I am not worried about totally changing my login system to make it more secure, it is a very simple system which is only used to store a users preferences for the site, please could we just sick to using SHA512.


回答1:


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', '$2a$07$addsomecustomstring$');
$correct   = crypt('Test', '$2a$07$addsomecustomstring$');
$wrong = crypt('tets',  '$2a$07$addsomecustomstring$');

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



回答2:


Since you already calculated hash above you no longer need to call hash function again in comparison:

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

instead of:

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


来源:https://stackoverflow.com/questions/31367850/verify-a-sha512-password-ifrowpassword-hashsha512-upass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!