-
ASN.1是什么?
ASN.1抽象语法标记(Abstract Syntax Notation One) ASN.1是一种 ISO/ITU-T 标准,描述了一种对数据进行表示、编码、传输和解码的数据格式。它提供了一整套正规的格式用于描述对象的结构,而不管语言上如何执行及这些数据的具体指代,也不用去管到底是什么样的应用程序。 -
本人在工作中涉及到ASN.1结构的场景
证书的公、私钥文件,做数据加密、签名、信封产生的数据都是ASN.1结构。 -
解析ASN.1
下面是一段简单的解析ASN.1结构,获取ASN.1结构的元素类型和值的代码。
如有图片中三种ASN.1结构的数据,要判断是其中的哪一种格式:
/**
* 获取sequence下第一个元素,并判断元素类型
* @param data
* @return
*/
private static String read_Asn1Data(byte[] data) {
ByteArrayInputStream bis = null;
ASN1InputStream ais = null;
String flag = "";
try {
bis = new ByteArrayInputStream(data);
ais = new ASN1InputStream(bis);
DERSequence sequence = (DERSequence) ais.readObject();
DEREncodable derEnd = sequence.getObjectAt(0);
DERObject readObject = derEnd.getDERObject();
if (readObject instanceof DERSequence) {
flag = "0";
}else if (readObject instanceof DERInteger) {
flag = "1";
}else if (readObject instanceof DERObjectIdentifier){
flag = "2";
}
} catch (IOException e) {
} finally {
try {
if (bis != null) bis.close();
if (ais != null) ais.close();
} catch (IOException e) {}
}
return flag;
}
/**
* 获取元素值
* @param data
* @return
*/
private static String read_Asn1Data(byte[] data) throws Exception {
ByteArrayInputStream bis = null;
ASN1InputStream ais = null;
ContentInfo contentInfo = null;
try {
bis = new ByteArrayInputStream(data);
ais = new ASN1InputStream(bis);
contentInfo = new ContentInfo((ASN1Sequence) ais.readObject());
} catch (IOException e) {
throw e;
} finally {
try {
if (bis != null) bis.close();
if (ais != null) ais.close();
} catch (IOException e) {}
}
return contentInfo.getContentType().getId();
}