Pkcs1RsaPublicKey.decode constructor

Pkcs1RsaPublicKey.decode(
  1. Uint8List data,
  2. PubTextSource? source
)

Decode from a sequence of bytes.

Implementation

Pkcs1RsaPublicKey.decode(Uint8List data, this.source) {
  String msg;

  try {
    List<ASN1Object> objects;

    try {
      objects = _asn1parseAll(data);
    } catch (e) {
      throw _Pkcs1Msg('bad ASN.1 encoding: $e');
    }

    if (objects.length != 1) {
      throw _Pkcs1Msg(
          'ASN.1 encoding has wrong number of objects (expecting 1, got ${objects.length})');
    }

    final topSequence = objects.first;
    if (topSequence is ASN1Sequence) {
      if (topSequence.elements.length != 2) {
        throw _Pkcs1Msg(
            'ASN.1 sequence wrong length (expecting 2, got ${topSequence.elements.length})');
      }

      final n = topSequence.elements[0];
      final e = topSequence.elements[1];
      if (n is ASN1Integer && e is ASN1Integer) {
        // Success

        modulus = n.valueAsBigInteger;
        exponent = e.valueAsBigInteger;
        return; // success
      } else {
        throw KeyBad('n and/or e are not ASN.1 Integers');
      }
    } else {
      throw _Pkcs1Msg('DER is not a sequence');
    }
  } on _Pkcs1Msg catch (e) {
    msg = e.message;
  } catch (e) {
    msg = 'unexpected: $e';
  }

  throw KeyBad('invalid PKCS #1 public key: $msg');
}