asn.1 java_java解析ASN.1结构

论坛 期权论坛 期权     
选择匿名的用户   2021-6-2 17:49   5717   0

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结构的数据,要判断是其中的哪一种格式:

a06ff3d63eda75242395807568e90b06.png7cd0554b032201be4b7574f1c6c2e61c.png535b0ad36ddc0e85ed666f822b6688df.png

/**

* 获取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();

}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP