verify method

bool verify({
  1. required String password,
  2. required String combined,
})

Verifies password against a combined string from hash.

Returns true if the password is correct, false otherwise.

The comparison is constant-time — execution time does not reveal whether the password was almost-right or completely wrong, which prevents timing attacks.

The iteration count is read from combined itself, so this method stays correct even for old hashes generated with a lower iteration count.

Throws CryptoException if combined is malformed.

Implementation

bool verify({required String password, required String combined}) {
  if (password.isEmpty) return false;
  try {
    final stored = HashedPassword.fromCombined(combined);
    final salt = base64Decode(stored.salt);
    final storedHash = base64Decode(stored.hash);

    final candidateHash = _pbkdf2(
      password: password,
      salt: salt,
      iterations: stored.iterations,
    );

    return _constantTimeEquals(storedHash, candidateHash);
  } on ArgumentError catch (e) {
    throw CryptoException(message: e.message.toString(), cause: e);
  } catch (e, st) {
    throw CryptoException(
      message: 'Password verification failed.',
      cause: e,
      stackTrace: st,
    );
  }
}