简体   繁体   中英

Php - Password hashing

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?

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM