decodePKCS1PublicKey static method

RSAPublicKey decodePKCS1PublicKey(
  1. Uint8List bytes
)

Format:

RSAPublicKey ::= SEQUENCE {
    modulus           INTEGER,  -- n
    publicExponent    INTEGER   -- e
}

See: https://tools.ietf.org/html/rfc8017#appendix-A

Implementation

// TODO: In fact this decodes both PKCS Public Key types
static RSAPublicKey decodePKCS1PublicKey(Uint8List bytes) {
  final topLevelParser = ASN1Parser(bytes);
  final topLevelBitStr = topLevelParser.nextObject();

  Uint8List pubKeyBytes;
  if (topLevelBitStr is ASN1BitString) {
    final pubKeySequence =
        ASN1Sequence.fromBytes(topLevelBitStr.contentBytes());
    pubKeyBytes = pubKeySequence.encodedBytes;
  } else {
    pubKeyBytes = bytes;
  }

  final parser = ASN1Parser(pubKeyBytes);

  if (!parser.hasNext()) {
    throw ArgumentError('Not a ASN.1 sequence');
  }

  final seq = parser.nextObject() as ASN1Sequence;

  if (seq.elements.length != 2) {
    throw ArgumentError(
        'RSAPublicKey must have exacly 2 elements in sequence');
  }

  final modulus = seq.elements[0] as ASN1Integer;
  final pubExp = seq.elements[1] as ASN1Integer;

  return RSAPublicKey(modulus.valueAsBigInteger!, pubExp.valueAsBigInteger!);
}