2

Given a sequence object, how can one iterate through the objects inside it? I've tried ASN1_TYPE_unpack_sequence but have no idea how to interpret the objects it returns.

Here is a toy example, the DER encoding of a sequence containing an empty octet string.

#include <stdio.h>
#include <openssl/asn1.h>

int main()
{
    unsigned char der_bytes[] = {48, 2, 4, 0};

    //Parse DER

    ASN1_TYPE *sequence = 0;
    const unsigned char * der_bytes_iterator = der_bytes;
    sequence = d2i_ASN1_TYPE(sequence, &der_bytes_iterator, sizeof der_bytes);

    //Make sure it was parsed properly

    if (der_bytes_iterator != der_bytes.data + sizeof der_bytes)
    {
        puts("Failed to consume DER string\n");
        return 1;
    }

    if (sequence->type != V_ASN1_SEQUENCE)
    {
        printf("Expected type tag %d, got %d.\n", V_ASN1_SEQUENCE, sequence->type);
        return 2;
    }

    //Try to iterate using ASN1_TYPE_unpack_sequece

    const ASN1_ITEM *item = ASN1_ITEM_rptr(ASN1_ANY);
    void * unpack_result = ASN1_TYPE_unpack_sequence(item, sequence);

    //Now what?
    return 0;
}

What is interesting is that {48, 0} encodes an empty sequence and {4, 0} encodes an empty octet string. So it seems like if I can only have the sequence's header parsed to know how long the header itself is and how much "payload" there is, I can just skip the header and keep parsing objects one by one until the payload is exhausted, no extra context required. Although this may be a dangerously naive view of how DER works.

Arya Pourtabatabaie
  • 705
  • 2
  • 7
  • 22

0 Answers0