getBytesFromPEMString static method

Uint8List getBytesFromPEMString(
  1. String pem, {
  2. bool checkHeader = true,
})

Helper function for decoding the base64 in pem.

Throws an ArgumentError if the given pem is not sourounded by begin marker -----BEGIN and endmarker -----END or the pem consists of less than two lines.

The PEM header check can be skipped by setting the optional paramter checkHeader to false.

Implementation

static Uint8List getBytesFromPEMString(String pem,
    {bool checkHeader = true}) {
  final List<String> lines = LineSplitter.split(pem.trim())
      .map((line) => line.trim())
      .where((line) => line.isNotEmpty)
      .toList();

  late final String base64;

  if (checkHeader) {
    if (lines.length < 2 ||
        !lines.first.startsWith('-----BEGIN') ||
        !lines.last.startsWith('-----END')) {
      throw ArgumentError('The given string does not have the correct '
          'begin/end markers expected in a PEM file.');
    }

    base64 = lines.sublist(1, lines.length - 1).join('');
  } else {
    base64 = lines.join('');
  }

  return Uint8List.fromList(base64Decode(base64));
}