How to get the size of DER structure?

114 views Asked by At

I need to learn the length of Der structure. It's used as a header for the cipher text file. My cipher writes the DER encoded data and the ciphertext back to back to the (cipher text) file.

I need to learn the size of the DER structure so I can pass it and only get the ciphertext from the cipher text file for decoding it. I know, I need to parse the length byte (or bytes) of header's outer asn1 sequence to get that info, but I don't know how to do it since I am not sure how many bytes it takes to store that length data.

I put the DER Header down below to give a basic idea. I would appreciate if you can take a look on it.

Header = \
        asn1_sequence(
                asn1_sequence(
                asn1_octetstring(salt)+
                asn1_integer(iter)+
                asn1_integer(len(key))
            ) +
            asn1_sequence(
                asn1_objectidentifier([2,16,840,1,101,3,4,1,2])+
                asn1_octetstring(iv_current)

            )+ 
            
            asn1_sequence(
                asn1_sequence(
                    asn1_objectidentifier([2,16,840,1,101,3,4,2,1])+
                    asn1_null()
                )+
                asn1_octetstring(digestinfo)
                )
        )
1

There are 1 answers

0
YaFred On

Your data is encoded with DER, this means it uses TLV (Tag Length Value) form.

To know the length of the Value, you will have to read the Tag and the Length.

Reading Tag and Length is not trivial and it is explained in Recommendation X.690

  • 8.1.2 Identifier octets
  • 8.1.3 Length octets

Depending on which language you want to use, you should be able to find some code to use or hack.

Example in Java

This lib would be used like this

BERReader reader = new BERReader(input);
reader.readTag();
reader.readLength();
reader.getLengthValue(); // gives you how many bytes you have to read