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