密码腌制 - 绝不匹配!

时间:2010-08-24 18:59:06

标签: php login registration salt

我很难弄清楚用户密码散列无法正常工作的原因。

我这样做的方法是常规方法,在注册时我创建了一个randam盐并与密码和商店结合,但是当我尝试匹配登录密码时,它们就失败了:(

<?php
class Model_users extends ModelType_DatabasePDO
{

 //...

 public function CheckCredentials($username,$password)
 {
  $statement = $this->prepare('SELECT user_id,user_salt,user_password FROM users WHERE user_username = :u');
  $statement->bindValue(':u',$username);

  if($statement->execute())
  {
   $user_data = $statement->fetch(PDO::FETCH_OBJ);

   //Create a new hash with salt
   $combined = $this->CombineHash($password,$user_data->user_salt);

   //Check the combination is correct!
   if($combined == $user_data->user_password)
   {
    return true;
   }

   var_dump($user_data->user_salt,$combined);
   return false;
  }
  return false;
 }

 //...

 public function AddUser($userdata)
 {
  if($userdata['username'] && $userdata['password'] && $userdata['email'] && $userdata['nickname'])
  {
   $statement = $this->prepare('INSERT INTO users (user_username,user_password,user_salt,user_email,user_nickname) VALUES (:username,:password,:salt,:email,:nickname)');

   //Generate hashes
   $salt = $this->GenerateSalt();
   $password = $this->CombineHash($userdate['password'],$salt);

   //Generate Data block for insert
   $data = array(
    ':username' => $userdata['username'],
    ':password' => $password,
    ':salt'  => $salt,
    ':email' => $userdata['email'],
    ':nickname' => $userdata['nickname']
   );

   if($statement->execute($data))
   {
    return true;
   }
  }
  return false;
 }

 private function GenerateSalt()
 {
  //Create a random md5 string:
  $first = md5( rand(0,100) . time() . microtime() . uniqid() );
  $second = md5( rand(0,100) . time() . microtime() . uniqid() );

  for($i=0;$i<=32;$i++)
  {
   $string = '';
   if($i % 2)
   {
    $string .= $first[$i];
   }else
   {
    $string .= $second[$i];
   }
  }
  return md5($string);
 }

 private function CombineHash($password,$hash)
 {
  return md5($password . $hash);
 }
}
?>

传递给方法的所有变量都是原始的,没有盐渍或加密,只是经过验证:/

此致

1 个答案:

答案 0 :(得分:8)

您的代码似乎有拼写错误

 $password = $this->CombineHash($userdate['password'],$salt);

$userdate必须为$userdata(e需要为a)。