Skip to content

Commit

Permalink
Early return false when hash length does not match expected
Browse files Browse the repository at this point in the history
  • Loading branch information
paulbalandan committed Dec 19, 2024
1 parent 9b07bca commit 26040bf
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
12 changes: 12 additions & 0 deletions src/Nexus/Password/Hash/Pbkdf2Hash.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,12 @@
*/
private int $length;

/**
* Used on `::verify()` to return early if provided hash's length
* does not match this hasher's instance's supposed hash length.
*/
private int $hashLength;

/**
* @param array{
* iterations?: int,
Expand Down Expand Up @@ -73,6 +79,8 @@ public function __construct(
$this->defaultIterations(),
self::DEFAULT_LENGTH,
);

$this->hashLength = \strlen($this->hash('password', salt: random_bytes(16)));
}

/**
Expand Down Expand Up @@ -107,6 +115,10 @@ public function verify(string $password, string $hash, string $salt = ''): bool
return false;
}

if (\strlen($hash) !== $this->hashLength) {
return false;
}

if (str_contains($hash, '$')) {
return false;
}
Expand Down
6 changes: 5 additions & 1 deletion tests/Password/Hash/Pbkdf2HashTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,11 @@ public function testPasswordVerify(): void
self::assertFalse($hasher->verify($pass3, $hash, $salt));
self::assertFalse($hasher->verify(
$pass2,
Password::fromAlgorithm(Algorithm::Argon2i)->hash($pass2),
substr(Password::fromAlgorithm(Algorithm::Argon2i)->hash($pass2), 0, 40),
));
self::assertFalse($hasher->verify(
$pass2,
(new Pbkdf2Hash(Algorithm::Pbkdf2HmacSha256, ['length' => 0]))->hash($pass2, salt: $salt),
));
}
}

0 comments on commit 26040bf

Please sign in to comment.