Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing ASN.1 binary data with Java

Tags:

I have binary ASN.1 data objects I need to parse into my Java project. I just want the ASN.1 structure and data as it is parsed for example by the BER viewer:

ASN.1 structure as shown in BER viewer

The ASN.1 parser of BouncyCastle is not able to parse this structure (only returns application specific binary data type).

What ASN.1 library can I use to get such a result? Does anybody has sample code that demonstrates how to parse an ASN.1 object?

BTW: I also tried several free ASN.1 Java compilers but none is able to generate working Java code given may ASN.1 specification.

like image 478
Robert Avatar asked Apr 17 '12 11:04

Robert


1 Answers

I have to correct myself - it is possible to read out the data using ASN.1 parser included in BouncyCastle - however the process is not that simple.

If you only want to print the data contained in an ASN.1 structure I recommend you to use the class org.bouncycastle.asn1.util.ASN1Dump. It can be used by the following simple code snippet:

ASN1InputStream bIn = new ASN1InputStream(new ByteArrayInputStream(data)); ASN1Primitive obj = bIn.readObject(); System.out.println(ASN1Dump.dumpAsString(obj)); 

It prints the structure but not the data - but by copying the ASN1Dump into an own class and modifying it to print out for example OCTET_STRINGS this can be done easily.

Additionally the code in ASN1Dump demonstrates to parse ASN.1 structures. For the example the data used in my question can be parsed one level deeper using the following code:

DERApplicationSpecific app = (DERApplicationSpecific) obj; ASN1Sequence seq = (ASN1Sequence) app.getObject(BERTags.SEQUENCE); Enumeration secEnum = seq.getObjects(); while (secEnum.hasMoreElements()) {     ASN1Primitive seqObj = (ASN1Primitive) secEnum.nextElement();     System.out.println(seqObj); } 
like image 185
Robert Avatar answered Oct 15 '22 16:10

Robert