douze2890241475
2015-10-25 23:58
浏览 28
已采纳

Php - 密码哈希

I've made this password class as you can see below:

<?php

namespace lib\Api;

class Password{

    private $password;
    private $salt;
    private $hash;

    public function __construct($password,$salt = ""){
        $this->password = $password;
        $this->salt = $salt;
        $this->generateHash($this->password,$this->salt);
    }
    public function generateHash($password,$salt = ""){
        $this->hash = hash('sha256',$password.$salt);
        return $this->hash;
    }
    public function get(){
        return $this->hash;
    }
    public function equals($password){
        if($this->hash == $password){
            return true;
        }
        return false;
    }
}

?>

So i use this to register a user in a user.php file/class

$this->password = (new Password($password,$this->getSalt()))->get();

, i also use this too again check this in a login.php file/class

if((new Password($this->password,$salt))->equals($password)){
    return true;
}
return false;

. Now i know that if you hash something that it depends in wich file it is, how it hashes the value. In this partical case it confuses me very much, as i both officialy hash it in the password.php file/class. How does this work and how can i solve it easily and nicely?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • douxunwei7083 2015-10-26 00:09
    最佳回答

    It's hard to understand what you're asking, but I bet you want to hash the value of $password before you check it's equality.

    <?php
    
    namespace lib\Api;
    
    class Password{
    
        private $password;
        private $salt;
        private $hash;
    
        public function __construct($password,$salt = ""){
            $this->password = $password;
            $this->salt = $salt;
            $this->hash = $this->generateHash($this->password);
        }
        public function generateHash($password){
            return hash('sha256',$password.$this->salt);
        }
        public function get(){
            return $this->hash;
        }
        public function equals($password){
            if($this->hash == $this->generateHash($password){
                return true;
            }
            return false;
        }
    }
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题