decodePemBlocks static method

List<Uint8List> decodePemBlocks(
  1. String pem,
  2. String label, {
  3. bool lenient = false,
})

Decodes all PEM blocks matching label.

Implementation

static List<Uint8List> decodePemBlocks(
  String pem,
  String label, {
  bool lenient = false,
}) {
  final escaped = RegExp.escape(label);
  final re = RegExp(
    '-----BEGIN $escaped-----([\\s\\S]*?)-----END $escaped-----',
    multiLine: true,
  );

  final matches = re.allMatches(pem);
  final out = <Uint8List>[];
  for (final m in matches) {
    final body = (m.group(1) ?? '').replaceAll(RegExp(r'\s+'), '');
    if (body.isEmpty) continue;
    try {
      out.add(Uint8List.fromList(base64Decode(body)));
    } catch (_) {
      if (!lenient) {
        rethrow;
      }
    }
  }
  return out;
}