parse static method

ASN1Sequence parse(
  1. MutableIterable bytes
)
override

Implementation

static ASN1Sequence parse(final MutableIterable bytes) {
  if (bytes.length < 3) {
    throw Exception('Invalid data!');
  }

  int tag = bytes.first;
  if (tag != ASN1Type.sequenceTag) {
    throw Exception('Invalid tag!');
  }
  bytes.mutate = bytes.skip(1);

  final children = <ASN1Object>[];

  if (bytes.first != 0x80) {
    final lengthBigInt = ASN1Object.decodeLength(bytes);
    int length = lengthBigInt.toInt();
    if (length == 0) {
      throw Exception('Invalid data');
    }

    if (bytes.length < length) {
      throw Exception('Invalid data');
    }

    final contentBytes = MutableIterable(bytes.take(length));
    bytes.mutate = bytes.skip(length);

    while (contentBytes.isNotEmpty) {
      children.add(ASN1Object.parse(contentBytes));
    }

    return ASN1Sequence(children);
  }

  bytes.mutate = bytes.skip(1);
  bool foundEnd = false;

  while (bytes.isNotEmpty) {
    final child = ASN1Object.parse(bytes);
    if (child is ASN1EndOfContent) {
      foundEnd = true;
      break;
    }
    children.add(child);
  }

  if (!foundEnd) {
    throw Exception('Invalid data. End of content not found');
  }

  return ASN1Sequence(children);
}