Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    }
}
like image 207
user2707535 Avatar asked Sep 17 '25 22:09

user2707535


1 Answers

I'm not sure if it's always correct/safe but you can use the password_get_info function. If the method can't guess the algorithm, we can assume that the string is not a hash.

function password_is_hash($password)
{
    return password_get_info($password)['algoName'] !== 'unknown';
}

This doesn't work for simple algorithms like sha1 or md5.

like image 101
Shaffe Avatar answered Sep 19 '25 12:09

Shaffe