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;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持