dvRsaPrivateKeyFromPem function

RSAPrivateKey dvRsaPrivateKeyFromPem(
  1. String pem
)

Decodes a PKCS#8 (BEGIN PRIVATE KEY) or PKCS#1 (BEGIN RSA PRIVATE KEY) PEM into an RSA private key: the private_key of a Google service account JSON file is the first.

Implementation

RSAPrivateKey dvRsaPrivateKeyFromPem(String pem) {
  final bool pkcs1 = pem.contains('BEGIN RSA PRIVATE KEY');
  final Uint8List der = base64.decode(
      pem.replaceAll(RegExp(r'-----[^-]+-----'), '').replaceAll(RegExp(r'\s'), ''));
  ASN1Sequence key = ASN1Parser(der).nextObject() as ASN1Sequence;
  if (!pkcs1) {
    // PrivateKeyInfo: version, algorithm, then the PKCS#1 key as an octet
    // string.
    final ASN1OctetString inner = key.elements![2] as ASN1OctetString;
    key = ASN1Parser(inner.valueBytes ?? inner.octets!).nextObject()
        as ASN1Sequence;
  }
  BigInt integer(int index) => (key.elements![index] as ASN1Integer).integer!;
  return RSAPrivateKey(integer(1), integer(3), integer(4), integer(5));
}