Sunday, September 16, 2012

BER-TLV Encoding of EMV Tags

ISO-8583 messages encode EMV tags using BER-TLV scheme in Field 55 of the message. The formal name of the encoding scheme is ASN.1 Basic Encoding Rule (ISO 8825).

The term TLV stands for Tag Length and Value (sometimes also referred to as Type, Length and Value). For EMV tags, the tag is usually 2-4 bytes in size; the length part is again 2-4 bytes in size,


Valid EMV Tag Names


Some sample EMV tag names are 81, 9F02, 9F26, 4F and 5A. You can find a complete list of tags and their description on EMV Lab's EMV Tags page. BER-TLV encoding rules divide the tag name (sometimes called tag type) into following parts: class (2 bits), primitive/ constructed identifier (1 bit) and tag name (5 bits followed by 0 or more bytes).

Take tag 9F26, for example. In binary, it's equivalent to byte1 = 1001 1111, and byte2 = 0010 0110. The first two bits are 10, which indicate that its class is "Context-Specific". The next bit is 0, which indicates that it's a primitive tag. The next 5 bits of the first byte are all 1, which indicates that the tag name is of the "long form" and we need to look at the next byte as well. All bits in byte 2 form part of the tag name. However, the highest bit of byte 2 (and all following bytes) must be turned on if there are more bytes included in the tag name. In our case, 9F26 is just two bytes; hence, the second byte has it's first bit turned off.


Constructed EMV Tags


The term "constructed" in the context of BER-TLV encoding means that the tag's value is a set of EMV tags itself; i.e., the tag has recursive BER-TLV encoding structure. Let' use Tag 71 as an example.

The hex value of 71 is represented as 0111 0001 in binary. The first two bits are 01 which indicate that it has an "Application" class. The third bit 1 indicates that the tag's value is a set of EMV tags itself. The rest of the bits 10001 indicate the actual tag identifier.

Now, one of the valid values of Tag 71 would be "9F06021234", i.e., the value of Tag 71 is the tag 9F06 along with it's length and content. However, the value "1234" will be incorrect as "1234" is not valid BER-TLV data.