Merge pull request #46186 from nextcloud/feat/validate-hash

feat: Add utility method to validate an IHasher hash
This commit is contained in:
Pytal 2024-07-04 17:45:04 -07:00 committed by GitHub
commit 915eef6429
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 47 additions and 1 deletions

View file

@ -79,7 +79,7 @@ class Hasher implements IHasher {
/**
* 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);
@ -190,4 +190,18 @@ class Hasher implements IHasher {
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';
}
}

View file

@ -47,4 +47,11 @@ interface IHasher {
* @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;
}

View file

@ -264,4 +264,29 @@ class HasherTest extends \Test\TestCase {
$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);
}
}