Search code examples
phpvalidationhashpasswords

How To Check If A Password Is A Hash - PHP


I have a user class that does some simple validation. I want to store all passwords as hashes using phpass. However, i dont want it to be the job of the User class to set the hash, This is the job of some other function. So if i have a simple function called setPassword how can i make sure the password is a hash. Does is_binary work?? I am not comparing hashes here i just simple want to make sure the password is a hash..shouldnt matter what kind md5..sha1...blah. I JUST WANT TO MAKE SURE THE PASSWORD IS A HASH.

example:

class User
{
    private password = NULL;
    private $errors = array();

    public function setPassword($password)
    {
        // make sure password is a hash...pseudo code
        if (!password_is_hash($password))
        {
            $this->errors[] = 'Invalid password';
            return $this;
        }
        $this->password = $password;
        return $this;
    } 

    public function getPassword()
    {
        return $this->password;
    }
}

Solution

  • As others have said hashes are strings and although (under conditions) you could say that an md5 or sha1 is always n characters you cannot guarantee that the given string is a hash.

    If what you want now is compare the user provided password with the hash saved in the db you could fetch the saved hash from the database and then hash the provided string with the same function used to create the saved hash and make sure they are equal and authenticate.