Is there a Java parser for BER-TLV?

倖福魔咒の 提交于 2019-11-27 18:30:04

问题


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.


回答1:


Tutorial in here gives a tips on how to parse BER-TLV. Using JACCAL




回答2:


You can use this BER-TLV parser: source code on git or download jar.
Examples:

How to parse

byte[] bytes = HexUtil.parseHex("50045649534157131000023100000033D44122011003400000481F");
BerTlvParser parser = new BerTlvParser(LOG);
BerTlvs tlvs = parser.parse(bytes, 0, bytes.length);

How to build

byte[] bytes =  new BerTlvBuilder()
                .addHex(new BerTag(0x50), "56495341")
                .addHex(new BerTag(0x57), "1000023100000033D44122011003400000481F")
                .buildArray();

Maven dependency

<dependency>
  <groupId>com.payneteasy</groupId>
  <artifactId>ber-tlv</artifactId>
  <version>1.0-10</version>
</dependency>



回答3:


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<String, String> parseTLV(String tlv) {
    if (tlv == null || tlv.length()%2!=0) {
        throw new RuntimeException("Invalid tlv, null or odd length");
    }
    HashMap<String, String> hashMap = new HashMap<String, String>();
    for (int i=0; i<tlv.length();) {
        try {
            String key = tlv.substring(i, i=i+2);

            if ((Integer.parseInt(key,16) & 0x1F) == 0x1F) {
                // extra byte for TAG field
                key += tlv.substring(i, i=i+2);
            }
            String len = tlv.substring(i, i=i+2);
            int length = Integer.parseInt(len,16);

            if (length > 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;
}



回答4:


The javaemvreader project contains some code to parse BER-TLV.




回答5:


I found Javacard classes for BER TLV. Hope those help




回答6:


Might be this free library can be useful for you. I've used this one for simple TLV parsing. Anyway it's with MIT license and you can modify it.

https://github.com/VakhoQ/tlv-encoder


来源:https://stackoverflow.com/questions/11473974/is-there-a-java-parser-for-ber-tlv

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!