Is there a Java parser for BER-TLV?

后端 未结 6 1920
暖寄归人
暖寄归人 2020-12-16 04:43

I\'m new to Java, so I would like to use the standard solution for, I think, the standard task. The length of tags and values ​​are not known.

6条回答
  •  感动是毒
    2020-12-16 04:51

    I made a simple parser based on the information provided here: http://www.codeproject.com/Articles/669147/Simple-TLV-Parser

    I don't know if this code support all the standard, but it works for me.

    public static Map parseTLV(String tlv) {
        if (tlv == null || tlv.length()%2!=0) {
            throw new RuntimeException("Invalid tlv, null or odd length");
        }
        HashMap hashMap = new HashMap();
        for (int i=0; i 127) {
                    // more than 1 byte for lenth
                    int bytesLength = length-128;
                    len = tlv.substring(i, i=i+(bytesLength*2));
                    length = Integer.parseInt(len,16);
                }
                length*=2;
    
                String value = tlv.substring(i, i=i+length);
                //System.out.println(key+" = "+value);
                hashMap.put(key, value);
            } catch (NumberFormatException e) {
                throw new RuntimeException("Error parsing number",e);
            } catch (IndexOutOfBoundsException e) {
                throw new RuntimeException("Error processing field",e);
            }
        }
    
        return hashMap;
    }
    

提交回复
热议问题