Skip to content

Commit

Permalink
Merge pull request #46186 from nextcloud/feat/validate-hash
Browse files Browse the repository at this point in the history
feat: Add utility method to validate an IHasher hash
  • Loading branch information
Pytal committed Jul 5, 2024
2 parents 4a8cf14 + 48b69c5 commit 915eef6
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 1 deletion.
16 changes: 15 additions & 1 deletion lib/private/Security/Hasher.php
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ public function hash(string $message): string {
/**
* Get the version and hash from a prefixedHash
* @param string $prefixedHash
* @return null|array Null if the hash is not prefixed, otherwise array('version' => 1, 'hash' => 'foo')
* @return null|array{version: int, hash: string} Null if the hash is not prefixed, otherwise array('version' => 1, 'hash' => 'foo')
*/
protected function splitHash(string $prefixedHash): ?array {
$explodedString = explode('|', $prefixedHash, 2);
Expand Down Expand Up @@ -190,4 +190,18 @@ private function getPrefferedAlgorithm(): string {

return $default;
}

public function validate(string $prefixedHash): bool {
$splitHash = $this->splitHash($prefixedHash);
if (empty($splitHash)) {
return false;
}
$validVersions = [3, 2, 1];
$version = $splitHash['version'];
if (!in_array($version, $validVersions, true)) {
return false;
}
$algoName = password_get_info($splitHash['hash'])['algoName'];
return $algoName !== 'unknown';
}
}
7 changes: 7 additions & 0 deletions lib/public/Security/IHasher.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,11 @@ public function hash(string $message): string;
* @since 8.0.0
*/
public function verify(string $message, string $hash, &$newHash = null): bool ;

/**
* Check if the prefixed hash is valid
*
* @since 30.0.0
*/
public function validate(string $prefixedHash): bool;
}
25 changes: 25 additions & 0 deletions tests/lib/Security/HasherTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -264,4 +264,29 @@ public function testHashUsePasswordDefault() {
$info = password_get_info($relativePath['hash']);
$this->assertEquals(PASSWORD_BCRYPT, $info['algo']);
}

public function testValidHash() {
$hash = '3|$argon2id$v=19$m=65536,t=4,p=1$czFCSjk3LklVdXppZ2VCWA$li0NgdXe2/jwSRxgteGQPWlzJU0E0xdtfHbCbrpych0';

$isValid = $this->hasher->validate($hash);

$this->assertTrue($isValid);
}

public function testValidGeneratedHash() {
$message = 'secret';
$hash = $this->hasher->hash($message);

$isValid = $this->hasher->validate($hash);

$this->assertTrue($isValid);
}

public function testInvalidHash() {
$invalidHash = 'someInvalidHash';

$isValid = $this->hasher->validate($invalidHash);

$this->assertFalse($isValid);
}
}

0 comments on commit 915eef6

Please sign in to comment.