needsRehash static method

bool needsRehash(
  1. String hashedPassword, {
  2. int targetCost = defaultCost,
})

Check if a hash needs to be rehashed (cost factor changed)

This is useful for upgrading password security when increasing the cost factor

hashedPassword - The bcrypt hash to check targetCost - The desired cost factor

Returns true if the hash should be regenerated with the new cost

Implementation

static bool needsRehash(String hashedPassword, {int targetCost = defaultCost}) {
  try {
    // Bcrypt hash format: $2a$10$...
    // Extract cost from hash
    final parts = hashedPassword.split('\$');
    if (parts.length < 3) return true;

    final currentCost = int.tryParse(parts[2]);
    if (currentCost == null) return true;

    return currentCost != targetCost;
  } catch (e) {
    return true;
  }
}