minor #34138 [Security/Core] add fast path when encoded password cannot match anything (nicolas-grekas)

This PR was merged into the 4.4 branch.

Discussion
----------

[Security/Core] add fast path when encoded password cannot match anything

| Q             | A
| ------------- | ---
| Branch?       | 4.4
| Bug fix?      | no
| New feature?  | no
| Deprecations? | no
| Tickets       | -
| License       | MIT
| Doc PR        | -

Only `MessageDigestPasswordEncoder` and `Pbkdf2PasswordEncoder` need this fast path: the sodium and the native encoders already implement it natively.

When a migrating encoder is used, a failed password validation fallbacks to all encoders. This makes the process slower than needed currently.

Commits
-------

c57f8f7f93 [Security/Core] add fast path when encoded password cannot match anything
This commit is contained in:
Robin Chalas 2019-10-27 11:11:28 +01:00
commit 32b227d004
2 changed files with 19 additions and 1 deletions

View File

@ -22,7 +22,8 @@ class MessageDigestPasswordEncoder extends BasePasswordEncoder
{
private $algorithm;
private $encodeHashAsBase64;
private $iterations;
private $iterations = 0;
private $encodedLength = -1;
/**
* @param string $algorithm The digest algorithm to use
@ -33,6 +34,13 @@ class MessageDigestPasswordEncoder extends BasePasswordEncoder
{
$this->algorithm = $algorithm;
$this->encodeHashAsBase64 = $encodeHashAsBase64;
try {
$this->encodedLength = \strlen($this->encodePassword('', 'salt'));
} catch (\LogicException $e) {
// ignore algorithm not supported
}
$this->iterations = $iterations;
}
@ -65,6 +73,10 @@ class MessageDigestPasswordEncoder extends BasePasswordEncoder
*/
public function isPasswordValid($encoded, $raw, $salt)
{
if (\strlen($encoded) !== $this->encodedLength || false !== strpos($encoded, '$')) {
return false;
}
return !$this->isPasswordTooLong($raw) && $this->comparePasswords($encoded, $this->encodePassword($raw, $salt));
}
}

View File

@ -32,6 +32,7 @@ class Pbkdf2PasswordEncoder extends BasePasswordEncoder
private $encodeHashAsBase64;
private $iterations;
private $length;
private $encodedLength;
/**
* @param string $algorithm The digest algorithm to use
@ -45,6 +46,7 @@ class Pbkdf2PasswordEncoder extends BasePasswordEncoder
$this->encodeHashAsBase64 = $encodeHashAsBase64;
$this->iterations = $iterations;
$this->length = $length;
$this->encodedLength = $encodeHashAsBase64 ? intdiv($length + 2, 3) << 2 : ($length << 1);
}
/**
@ -72,6 +74,10 @@ class Pbkdf2PasswordEncoder extends BasePasswordEncoder
*/
public function isPasswordValid($encoded, $raw, $salt)
{
if ((0 < $this->length && \strlen($encoded) !== $this->encodedLength) || false !== strpos($encoded, '$')) {
return false;
}
return !$this->isPasswordTooLong($raw) && $this->comparePasswords($encoded, $this->encodePassword($raw, $salt));
}
}