parsePem function

Iterable parsePem(
  1. String pem
)

Implementation

Iterable parsePem(String pem) sync* {
  var lines = pem
      .split('\n')
      .map((line) => line.trim())
      .where((line) => line.isNotEmpty)
      .toList();

  final re = RegExp(r'^-----BEGIN (.+)-----$');
  for (var i = 0; i < lines.length; i++) {
    var l = lines[i];
    var match = re.firstMatch(l);
    if (match == null) {
      throw ArgumentError('The given string does not have the correct '
          'begin marker expected in a PEM file.');
    }
    var type = match.group(1);

    var startI = ++i;
    while (i < lines.length && lines[i] != '-----END $type-----') {
      i++;
    }
    if (i >= lines.length) {
      throw ArgumentError('The given string does not have the correct '
          'end marker expected in a PEM file.');
    }

    var b = lines.sublist(startI, i).join('');
    var bytes = base64.decode(b);
    yield _parseDer(bytes, type);
  }
}