Search code examples
cemvtlv

how to parse 3 byte length BER-TLV TAG


I am working with some EMV tags which most of them have a length of 1 or 2 bytes for example 9F02, 81,.. I understand that there is a certain bit configuration to know how I can determine the tag length for determine if a tags is 2 byte length or larger, Im using:

unsigned char tags[]={0x9F,0x02};
if((tags[0]&0x1F)==0x1F){
  ...
}

but I dont know to do when I have some tag larger than this.

Im working with EMV Data, Im testing with certification card , I'm receiving these tags are: DF8111, DF8119, DF811E, DF812C they are relate to CVM.


Solution

  • According to

    EMV 4.3 Book 3

    , Annex B - Rules for BER-TLV Data Objects sections B1, B2 that was linked above, you should check the bit 8 in the current byte in order to know if there are more byte in tag, assuming that you are using c/c++ (as you tag it in this post) here is a code that could be taken in order to check that condition, I commented the code bellow where the condition is and could used by you.

            int start = 0;
            int end = start + len;
            while (start < end) {
    
                int tag = src[start++] & 0xFF;
    
                if (tag == 0x00 || tag == 0xFF) {
                    continue;
                }
    
                if ((tag & 0x1F) == 0x1F) {
                    if (start >=  len ) {
                        break;
                    }
    
                    tag = (tag << 8) | src[start++] & 0xFF;
                    // tag has 3 bytes (0xFFFFFF)
                    /// check this line it could what you need.
                    if ((tag & 0x80) != 0) {
                        if (start >=  len ) {
                            break;
                        }
                        //// Append third byte to the Tag.
                        tag = (tag << 8) | src[start++] & 0xFF;
                    } 
                }
           /// ...
    } ///end while
    

    I hope this help you.