validate method

void validate()

Validate this PHC string. Throws ArgumentError when any field is invalid.

Implementation

void validate() {
  // Character sets follow the PHC string format specification, but the salt
  // and hash stay permissive to accept Modular Crypt Format strings such as
  // bcrypt (whose base64 alphabet uses '.').
  // https://github.com/C2SP/C2SP/blob/main/phc-strings.md
  final versionRe = RegExp(r'^(0|[1-9][0-9]*)$');
  final alnumRe = RegExp(r'^[a-z0-9-]{1,32}$');
  final valueRe = RegExp(r'^[a-zA-Z0-9/+.-]+$');

  // id
  if (!alnumRe.hasMatch(id)) {
    throw ArgumentError.value(
        id, 'id', 'must be [a-z0-9-] and under 32 characters');
  }

  // version (optional)
  if (version != null && !versionRe.hasMatch(version!)) {
    throw ArgumentError.value(
        version, 'version', 'must be decimal digits without leading zeros');
  }

  // params (optional)
  if (params != null) {
    for (final e in params!.entries) {
      final k = e.key;
      final v = e.value;
      if (!alnumRe.hasMatch(k)) {
        throw ArgumentError.value(
            k, 'params.key', 'must be [a-z0-9-] and under 32 chars');
      }
      if (k == 'v') {
        throw ArgumentError.value(
            k, 'params.key', 'reserved; use version field instead');
      }
      if (v.isEmpty) {
        throw ArgumentError.value(v, 'params[$k]', 'value is empty');
      } else if (!valueRe.hasMatch(v)) {
        throw ArgumentError.value(
            v, 'params[$k]', 'value has invalid characters');
      }
    }
  }

  // salt (optional)
  if (salt != null && !valueRe.hasMatch(salt!)) {
    throw ArgumentError.value(
        salt, 'salt', 'must be characters in [a-zA-Z0-9/+.-]');
  }

  // hash (optional)
  if (hash != null && !valueRe.hasMatch(hash!)) {
    throw ArgumentError.value(
        hash, 'hash', 'must be characters in [a-zA-Z0-9/+.-]');
  }
}