Search code examples
asn.1tlvber

When reading BERTLV, when do you stop?


I have the following BERTLV: 61394F0BA00000030800001001234579074F05A000012345500E49442D4F6E65205049562042494F5F50107777772E6F626572746875722E636F6D7F66080202800002028000

I'm trying to parse this in a recursive way, so I am treating the first part as a TLV.

Tag: 0x61, Len: 0x39, Value: 4F0BA00000030800001001234579074F05A000012345500E49442D4F6E65205049562042494F5F50107777772E6F626572746875722E636F6D

Then I break it down further, and get

Tag: 0x4F, Len: 0x0B, Value: A000000308000010012345

Now, how do I stop? At this point, I know this value is the last leg of this TLV and is not another nested TLV.


Solution

  • Ok after much digging, I found out what the simple TAG is actually more than just a number, the TAG itself actually encoded a brunch of information in there. I order to find out whether the TLV contains nested TLV so that my code would know when to continue processing and when to stop, I had to decode the TAG.

    So the TAG contains 8 bits, and each one of them have special meaning:

    TLV TAG and their bits meaning

    The bit that I needed was B5 in order to determine whether the current TLV is Constructed or not... when is Constructed it means that current TLV consists of multiple TLV, so for my code, I am using this information to recursively dig in the nested TLV.

    When the TLV is not Constructed that is my stopping case to bubble back up.

    Here is my recursive function output by parsing the data and checking the bit B5 in TAG:

    11:20:38.428 Parsing: 61394F0BA00000030800001000010079074F05A000000308500E49442D4F6E65205049562042494F5F50107777772E6F626572746875722E636F6D7F66080202800002028000
    11:20:38.436 Constructed Data Object
    11:20:38.437 Parsing: 4F0BA00000030800001000010079074F05A000000308500E49442D4F6E65205049562042494F5F50107777772E6F626572746875722E636F6D
    11:20:38.437 Primitive Data Object
    11:20:38.437 tag: 79, len: 11, value: A000000308000010000100
    11:20:38.437 Constructed Data Object
    11:20:38.437 Parsing: 4F05A000000308
    11:20:38.437 Primitive Data Object
    11:20:38.437 tag: 79, len: 5, value: A000000308
    11:20:38.437 Primitive Data Object
    11:20:38.437 tag: 80, len: 14, value: 49442D4F6E65205049562042494F
    11:20:38.437 MultiByte tag
    11:20:38.437 Primitive Data Object
    11:20:38.437 tag: 24400, len: 16, value: 7777772E6F626572746875722E636F6D
    11:20:38.438 MultiByte tag
    11:20:38.438 Constructed Data Object
    11:20:38.438 Parsing: 0202800002028000
    11:20:38.438 Primitive Data Object
    11:20:38.438 tag: 2, len: 2, value: 8000
    11:20:38.438 Primitive Data Object
    11:20:38.438 tag: 2, len: 2, value: 8000