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 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘