Search code examples
phppasswordscrypt

Password works even with extra characters


I have two methods that I am using. When a user creates an account I call this method to make a secure password hash for them to save into the database:

public function createPassword($password){
    $salt = hash("sha256", time() . uniqid() . rand(1, 1000));
    return crypt($password, $salt);
}

It returns a salt which I then save into the database in the password column.

Next when a user logs into his/her account I select their info from the database and pass it to this function which then is supposed to verify their password.

public function verifyPassword($password, $salt){
    if(crypt($password, $salt) == $salt){
        return true;
    }
    return false;
}

The issue is that I have found a password that if I put the correct password in it works, but if I add extra characters to the end of the password it still works. This shouldn't happen. am I doing something wrong or is this a bug in php?

For security I am not using the real password below

// Create during registration
$salt = $obj->createPassword('abc123');
// Save to database here

then:

// Get row from database save array $row
if($obj->verifyPassword($_POST["passwd"], $row["password"])){
    // Log user in
}

Here are my tests:

abc123          // Works
abc12           // doesn't work
abc12jfjf       // doesn't work
abc123123       // Works
abc123asdfadffa // Works

So, it looks as if as long as the string starts with the real password anything after is fine...


Solution

  • This may depend on the encryption method you are using. In your example, is the actually password you are using 8 characters?

    If so, then any characters past the 8th are truncated.

    https://bugs.php.net/bug.php?id=11240

    To avoid this behavior, use MD5 encryption.