parseFromPem static method

RSAAsymmetricKey parseFromPem(
  1. String pem
)

Parses the PEM key no matter it is public or private, it will figure it out.

Implementation

static RSAAsymmetricKey parseFromPem(String pem) {
  final lines = pem
      .split('\n')
      .map((String line) => line.trim())
      .where((String line) => line.isNotEmpty)
      .toList();

  final headerIndex = lines.indexWhere((s) => s.contains(pkcsStartHeader));
  final footerIndex = lines.indexWhere((s) => s.contains(pkcsStartFooter));

  final body = lines.sublist(headerIndex + 1, footerIndex).join('');
  final bodyBytes = base64Decode(body);

  if (lines[0].contains(pkcs1PublicHeader)) {
    return decodePKCS1PublicKey(bodyBytes);
  } else if (lines[0].contains(pkcs1PrivateHeader)) {
    return decodePKCS1PrivateKey(bodyBytes);
  } else if (lines[0].contains(pkcs8PrivateHeader)) {
    return decodePKCS8PrivateKey(bodyBytes);
  } else if (lines[0].contains(certPublicKeyHeader)) {
    return decodeCertPublicKey(bodyBytes) as RSAPublicKey;
  }

  throw ArgumentError('Could only parse PCKS1/PKCS8 RSA PEM files');
}