Tuesday 26 September 2017

BER TLV Tag Parsing in Java



Q: Java code for BER TLV tag identification and Length Identification of EMV Fields from Device or HOST ??

Solution:

I tried writing stuff for myself and I thought it helps to you on reading  dynamic TLV tag name and Length in java





  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
package com.ohms.rnd.emv;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;


/**
 * 
 * Ref: page :173:Coding of the Tag Field of BER-TLV Data Objects 
 * http://mech.vub.ac.be/teaching/info/mechatronica/finished_projects_2007/Groep%201/Smartcard_files/EMV%20v4.1%20Book%203.pdf
 * 
 * @author 
 *
 */
public class BERTLV {


 private static Set<String> specialtags= Arrays.stream(new String[]{/*"91","71","72"*/}).collect(Collectors.toSet());;
 public static void main(String[] args) {
  
  
  List<String> tlvs= new ArrayList<>();
  //Request Tags
  tlvs.add("77299f2701009f360200419f2608c74d18b08248fefc9f10120110201009248400000000000000000029ff");
  tlvs.add("9f2701009f360200419f2608c74d18b08248fefc9f10120110201009248400000000000000000029ff");
  tlvs.add("9F4005FF80F0F001");
  tlvs.add("9F0206000000012345");
  tlvs.add("9F0306000000004000");
  tlvs.add("9F26088E19ED4BCA5C670A");
  tlvs.add("82025C00");
  tlvs.add("5F340102");
  tlvs.add("9F3602000A");
  tlvs.add("9F0702FF00");
  tlvs.add("9F080208C1");
  tlvs.add("9F09021001");
  tlvs.add("8A025931");
  tlvs.add("9F3403A40002");
  tlvs.add("9F270180");
  tlvs.add("9F1E0853455249414C3132");
  tlvs.add("9F0D05F040008800");
  tlvs.add("9F0E05FCF8FCF8F0");
  tlvs.add("9F0F05FCF8FCF8F0");
  tlvs.add("5F28020840");
  tlvs.add("9F390100");
  tlvs.add("9F3303010101");
  tlvs.add("9F1A020840");
  tlvs.add("9F350122");
  tlvs.add("95050000048000");
  tlvs.add("5F2A020840");
  tlvs.add("9A03140131");
  tlvs.add("9B024800");
  tlvs.add("9F2103123456");//////////////////////
  tlvs.add("9C0100");
  tlvs.add("9F370400BC614E");
  tlvs.add("4F07A0000000031010");
  tlvs.add("9F0607A0000000031010");
  tlvs.add("9F7C0412345678");
  tlvs.add("8407A0000000031010");
  tlvs.add("9F6E05123456789A");
  tlvs.add("9F6E0401020304");
  tlvs.add("9F6E0401020304");
  tlvs.add("9F1006010A03600000");
  tlvs.add("9F5B052000000000");
  tlvs.add("9F4104000001B3");
  tlvs.add("8C209F02069F03069F1A0295055F2A029A039C019F37049F35019F45029F34039B028D08910A8A0295059B028E1000000000000000005F0341035E030203");
  tlvs.add("DFEE250202034F07A0000000031010500B5669736120437265646974560057134072640000000008D22122011143878089629F5A08407264000000000882021C008407A000000003101087008A025A33950580000000009A031709149B0268009C01005F24032212315F2A0208405F300202015F3401019F02060000000001009F03060000000000009F0607A00000000310109F0702FF009F080200969F090200969F1101019F0D05B078FC88009F0E0500000000009F0F05B078FC98009F120E56495341204175737472616C69619F1A0208409F1E085465726D696E616C9F21030842249F33036028C89F34035E03009F3501219F360200B79F370441946B209F38009F3901059F3C009F4005F000F0A0019F4104000000099F5301529F6E009F7C005F201A434152442030332F2D20415544202020202020202020202020205F280200365F2D02656E5F5600DFEE2300DFEE2600FFEE01009F2608D2A4BD91753ADEFF9F2701809F100706010A03A0A000DFEF4C06002700100000DFEF4D373B343037323634303030303030303030383D32323132323031313134333837383038393632393F34303732363430303030303030303038");
  
  //response
  tlvs.add("910A2263BCC1C2D9C4420013");
  tlvs.add("710A0102030405060708090A");
  tlvs.add("720A0102030405060708090A");
  tlvs.add("8C209F02069F03069F1A0295055F2A029A039C019F37049F35019F45029F34039B028D08910A8A0295059B028E1000000000000000005F0341035E030203");
  

  
  tlvs.forEach(x-> {
   try {
    parseBERTLVTag(x);
   } catch (DecoderException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  });
  
  
  
  
  
 }
 
 //B1 Coding of the Tag Field of BER-TLV Data  Objects 
 public static void parseBERTLVTag(String tlv) throws DecoderException 
 {
  if(tlv==null || "".equalsIgnoreCase(tlv)) return;
  
  System.out.println("============= START ["+tlv+"]==================");

  
  boolean inTagRead= true;
  Map<String,String> tags= new HashMap<>();
  
  StringBuilder _tmp = new StringBuilder();
  String lastTag = null;
  int old_index = 0;
  boolean isFirstTagByte = true;
  
  boolean more=true;
  while (more) 
  {
   
   String hByte = tlv.substring(old_index,(old_index = old_index+2));
   if(inTagRead)
   {
    if(isLastTagByte(hByte, isFirstTagByte))
    {
     inTagRead=false;
     _tmp.append(hByte);
     lastTag =  _tmp.toString();
     System.out.println("Tag["+lastTag+"]");
     tags.put(lastTag, null);
     _tmp= new StringBuilder(); 
    }else
    {
     _tmp.append(hByte);
    }
    
    isFirstTagByte = false;
    
   }else//Length
   {
    
    isFirstTagByte = true;
    if(!isSpecialTag(lastTag)) {
    
     if(isLastLengthByte(hByte)) {
      inTagRead=true;
      _tmp.append(hByte);
      int len =  Integer.parseInt(_tmp.toString(), 16 );
      //read len*2
      System.out.println(" Length ["+len+"]");
      String data =  tlv.substring(old_index, (old_index = old_index+len*2));
      String tmpData= lastTag+":"+_tmp.toString()+":h"+data;
      System.out.println(" Data ["+tmpData+"]");
      _tmp = new StringBuilder();

      tags.put(lastTag, tmpData); 
      
     }else
     {
      _tmp.append(hByte);
     }

    }else { //Special tag not TLV format
     
     
     
     int len=10;
     String data =  "";//tlv.substring(old_index, (old_index = old_index+len*2));
     String tmpData= lastTag+":0A:h"+data;
     System.out.println(" Data ["+tmpData+"]");
     _tmp = new StringBuilder();

     tags.put(lastTag, tmpData);
     
    }
        
    
    
   }
   
   more= tlv.length()<=old_index?false:true;
//   if(tlv.length()<=old_index) more=false;
   
    
   
   
  }//END OF WHILE
  
  
  System.out.println("------------  as MAP  ---------------------");
  tags.forEach((x,y)->{System.out.println("Tag["+x+"] Value["+y+"]");});
  System.out.println("===============================");
  
 }
 
 
 public static boolean isLastTagByte(String onehexByte, boolean firstByte) throws DecoderException
 {
  
   byte tagByte = Hex.decodeHex(onehexByte.toCharArray())[0];
   
   if(firstByte && (tagByte & 0x1f) == 0x1f) {
    return false;
   } else if (!firstByte && (tagByte & 0x80) == 0x80) {
    return false;
   } else {
    return true;
   }
 }
 
 public static boolean isLastLengthByte(String onehexByte) {
  
  String binVal = new BigInteger(onehexByte, 16).toString(2);
  binVal= fillChars(false, binVal, 8, "0"); 
  if(binVal.startsWith("0")) return true;
   
   return true;

 }
 public static String fillChars(String fillChar,int times)
 {
  StringBuffer builder=new StringBuffer();
  if(fillChar==null)
   return "";
  for (int i = 0; i < times; i++) 
  {
   builder.append(fillChar);
  }
  return builder.toString();
 }
 public static String fillChars(boolean isLeftJustified,String data,int length,String fillChar)
 {
  StringBuffer ret=new StringBuffer(); 
  String fill=null;
  if(data!=null && !data.equalsIgnoreCase(""))
  {
   
   int datLength=data.length();
   int diff=-1;
   if(datLength<length)
   {
    diff=length-datLength; 
    
    fill=fillChars(fillChar, diff);
    
    if(isLeftJustified)
    {
     ret.append(data);
     ret.append(fill);
    }else
    {
     ret.append(fill);
     ret.append(data);
    }
   }else if(datLength==length)
   {
    ret.append(data);
   }
   
  }else
  {
   
   ret.append(fillChars(fillChar, length));
   
  }
 return ret.toString(); 
 }
 
 private static boolean isSpecialTag(String tagName) 
 {
  return specialtags.contains(tagName);
 }
 
 
}

2 comments:

  1. I wish to know a little about is isLastTagByte and isLastLengthByte methods there maybe a case where the tag is of 3 bytes then it could fail right

    ReplyDelete

Please comment here