是否有用于 BER-TLV 的 Java 解析器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11473974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a Java parser for BER-TLV?
提问by Zharro
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.
我是 Java 新手,所以我想将标准解决方案用于标准任务。标签和值的长度未知。
回答by Maksym Pecheniuk
You can use this BER-TLV parser: source code on git.
Examples:
How to parse
您可以使用这个 BER-TLV 解析器:git 上的源代码。
示例:
如何解析
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
Maven 依赖
<dependency>
<groupId>com.payneteasy</groupId>
<artifactId>ber-tlv</artifactId>
<version>1.0-10</version>
</dependency>
回答by HelmiB
回答by vlp
The javaemvreaderproject contains some code to parse BER-TLV.
回答by grep
Might be this free librarycan be useful for you. I've used this one for simple TLV parsing. Anyway it's with MIT license and you can modify it.
可能这个免费图书馆对你有用。我已经将这个用于简单的 TLV 解析。无论如何,它具有 MIT 许可证,您可以对其进行修改。
https://github.com/VakhoQ/tlv-encoder
回答by Ignacio A. Poletti
I made a simple parser based on the information provided here: http://www.codeproject.com/Articles/669147/Simple-TLV-Parser
我根据这里提供的信息做了一个简单的解析器: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;
}