Friday, October 22, 2010

ASN.1

A few days earlier I have to work on a system using ASN.1 protocol. I did some research to find a solution written in java for BER so that i can test the files encoded through ASN.1; to my surprise the libraries I found further confuse me. I didn't want to blame any one but people have written more complicated things on the subject thus making more confusing for a beginner to understand what the protocol is and how he should write some code to start. So I decided to write a simple piece of code myself.
I am not writing here about the ASN.1 protocol itself; I am writing a piece of code to start decoding a file in ASN.1 protocol using BER. The structure of ASN.1 is like TLV ( which is tag, length, value). You can read more about ASN.1 and BER at wiki.
Reading tag of ASN.1


private String readTag(DataInputStream inputStream)
{

byte[] bytes = readBytes(inputStream, 1);

Of course we can easily read bytes to a byte array, then covert this byte array to hex like

String hexValue = byteArraytoHex(bytes).trim();


If you need help converting byte array to hex please take a look at previous post here
Rest is simple

int tagClass = (bytes[0] & 0xC0) >> 6;

int tagType = (bytes[0] & 0x20) >> 5;
int tag = bytes[0] & 0x1F;
if (tag == 31)
{
StringBuffer buffer = new StringBuffer(byteArraytoHex(bytes).trim());
bytes = readBytes(inputStream, 1);

buffer.append(byteArraytoHex(bytes).trim());
BitIterator iterator = new BitIterator(bytes);
String mostSignificant = iterator.getBits(1);
while (!mostSignificant.equals("0"))
{
bytes = readBytes(inputStream, 1);

buffer.append(byteArraytoHex(bytes).trim());
iterator = new BitIterator(bytes);
mostSignificant = iterator.getBits(1);
}
hexValue = buffer.toString();
}

// System.out.print("Tag Class = ");
// switch (tagClass)
// {
// case 0:
// System.out.print("Universal");
// break;
// case 1:
// System.out.print("Application");
// break;
// case 2:
// System.out.print("Context-Specific");
// break;
// case 3:
// System.out.print("Private");
// break;
// }
//
// System.out.print(" ------ Type = ");
//
// switch (tagType)
// {
// case 0:
// System.out.print("Primitive");
// break;
// case 1:
// System.out.print("Constructed");
// break;
// }
//
// System.out.println(" ------- tage Value = " + tag);

return hexValue;

}



And you might need BitIterator class too; can be found here

No comments:

Post a Comment