Skip to content

Commit

Permalink
Add bcrypt errors if verification fails on an invalid hash. This occu…
Browse files Browse the repository at this point in the history
…rs if verifying new-style hashes on old versions
  • Loading branch information
ircmaxell committed Jun 10, 2013
1 parent 7986e7e commit 78f081a
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
23 changes: 22 additions & 1 deletion library/Zend/Crypt/Password/Bcrypt.php
Original file line number Diff line number Diff line change
Expand Up @@ -108,11 +108,32 @@ public function create($password)
*
* @param string $password
* @param string $hash
* @throws Exception\RuntimeException when the hash is unable to be processed
* @return bool
*/
public function verify($password, $hash)
{
return ($hash === crypt($password, $hash));
$result = crypt($password, $hash);
if ($result === $hash) {
return true;
}
if (strlen($result) <= strlen($hash)) {
/* This should only happen if the algorithm that generated hash is
* either unsupported by this version of crypt(), or is invalid.
*
* An example of when this can happen, is if you generate
* non-backwards-compatible hashes on 5.3.7+, and then try to verify
* them on < 5.3.7.
*
* This is needed, because version comparisons are not possible due
* to back-ported functionality by some distributions.
*/
throw new Exception\RuntimeException(
'The supplied password hash could not be verified. Please check ' .
'backwards compatibility settings.'
);
}
return false;
}

/**
Expand Down
16 changes: 16 additions & 0 deletions tests/ZendTest/Crypt/Password/BcryptTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,22 @@ public function testVerify()
$this->assertFalse($this->bcrypt->verify(substr($this->password, -1), $this->bcryptPassword));
}

public function testVerifyFailureVersion()
{
$test = (substr(crypt('test', '$2y$04$012345678901234567890123456789'), 0, 3) === '$2y');
if (!$test) {
// We don't support new style hashes, test verify failure
$hash = '$y2$14$MTIzNDU2Nzg5MDEyMzQ1NeWUUefVlefsTbFhsbqKFv/vPSZBrSFVm';
$this->setExpectedException('Zend\Crypt\Password\Exception\RuntimeException',
'The supplied password hash could not be verified. Please check ' .
'backwards compatibility settings.'
);
$this->bcrypt->verify('test', $hash);
} else {
$this->skip('Test requires PHP which does not support $2y hashes (<5.3.7)');
}
}

public function testPasswordWith8bitCharacter()
{
$password = 'test' . chr(128);
Expand Down

0 comments on commit 78f081a

Please sign in to comment.