java对asn.1格式数据编解码示例

    工作中用到了asn.1格式数据,所以这里对asn.1格式的编解码做一个简单的介绍,主要通过程序来构建与解析asn.1格式数据。asn.1格式一般分为三个部分,分别是类型、长度、值,也就是Tag,Length,Value,简称TLV格式。

    类型一般分为以下几种:

    sequence,也叫集合和结构

    integer,整数

    utf8string,字符串

    boolean,布尔类型

    time,时间类型

    下面构建一个maven项目,引入项目依赖:

<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-ext-jdk15on</artifactId>
    <version>1.65</version>
</dependency>

    定义一个student的实体类,继承ASN1Object:

package com.xxx.asn1;

import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.DERUTF8String;
import org.bouncycastle.asn1.x509.Time;

public class Student extends ASN1Object {
	
	private ASN1Integer id;
	private DERUTF8String name;
	private ASN1Integer age;
	private Time createDate;
	
	public void setId(ASN1Integer id) {
		this.id = id;
	}
	public void setName(DERUTF8String name) {
		this.name = name;
	}
	public void setAge(ASN1Integer age) {
		this.age = age;
	}
	public void setCreateDate(Time createDate) {
		this.createDate = createDate;
	}
	
	public ASN1Integer getId() {
		return id;
	}
	public DERUTF8String getName() {
		return name;
	}
	public ASN1Integer getAge() {
		return age;
	}
	public Time getCreateDate() {
		return createDate;
	}
	
	public Student() {
		// TODO Auto-generated constructor stub
	}
	
	

	public Student(ASN1Integer id, DERUTF8String name, ASN1Integer age,
			Time createDate) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
		this.createDate = createDate;
	}
	
	@Override
	public ASN1Primitive toASN1Primitive() {
		ASN1EncodableVector vector = new ASN1EncodableVector();
		vector.add(id);
		vector.add(name);
		vector.add(age);
		vector.add(createDate);
		return new DERSequence(vector);
	}

}

    定义一个主类App,来分别构建asn.1和解析asn.1格式数据:

package com.xxx.asn1;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;

import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.ASN1SequenceParser;
import org.bouncycastle.asn1.DERUTF8String;
import org.bouncycastle.asn1.x509.Time;
import org.bouncycastle.util.encoders.Base64;

public class App {
	
	/**
	 * 构建asn.1
	 */
	public static void buildStudent(){
		Integer id = 1;
    	String name = "buejee";
    	Integer age = 18;
    	Time createDate = new Time(new Date());
    	try {
			
    		Student student = new Student(new ASN1Integer(id),
    				new DERUTF8String(name),
    				new ASN1Integer(age),
    				createDate);
    		String data = Base64.toBase64String(student.getEncoded());
    		System.out.println(data);
    		OutputStream out = new FileOutputStream(new File("student.cer"));
    		out.write(data.getBytes());
    		out.flush();
    		out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 解析asn.1
	 */
	public static void resolveStudent(){
		byte[] data = Base64.decode("MB0CAQEMBmJ1ZWplZQIBEhcNMjAwNTE1MTUxNDAzWg==");
		ASN1InputStream ais = new ASN1InputStream(data);
		ASN1Primitive primitive = null;
		try {
			while((primitive=ais.readObject())!=null){
				System.out.println("sequence->"+primitive);
				if(primitive instanceof ASN1Sequence){
					ASN1Sequence sequence = (ASN1Sequence)primitive;
					ASN1SequenceParser parser = sequence.parser();
					ASN1Encodable encodable = null;
					while((encodable=parser.readObject())!=null){
						primitive = encodable.toASN1Primitive();
						System.out.println("prop->"+primitive);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				ais.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
    public static void main( String[] args ){
    	//buildStudent();
    	resolveStudent();
    }
}

    分别运行两个方法,第一个是buildStudent()是构建一个asn.1格式数据,我们最后将他转为base64字符串,打印并存储在student.cer文件中。

     

    打印的结果和保存在student.cer中的结果是一样的。我们可以通过asn1view工具查看这个内容:

    sequence部分:

    

    第一个integer:

    

    string:

    

    第二个integer:

    

      time :

     

    这所有的内容都符合我们在代码中定义的数据:

     

    id=1,name=buejee,age=18,createDate=(20)20/05/15 15:36:43,时间是世界时间,所以东八区的话应该是(20)20/05/15 23:36:43,都是正确的。

    我们再来看看解析,调用resolveStudent()方法,控制台打印结果如下:

    

    数据读出来了。跟我们构建时传入的参数一样。

    本文的代码和工具asn1view都会放到github上,有需要的可以查看。 

  • 7
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论
在Android上使用ASN.1编解码,可以采用Bouncy Castle库提供的API实现。 首先,需要在项目中导入Bouncy Castle库,可以通过Gradle添加以下依赖: ``` implementation 'org.bouncycastle:bcprov-jdk15on:1.68' implementation 'org.bouncycastle:bcpkix-jdk15on:1.68' ``` 接下来,可以使用Bouncy Castle提供的ASN.1编解码API实现对ASN.1格式数据编解码。下面是一个简单的示例代码: ```java import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1OutputStream; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.DERInteger; import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.DERSequence; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; public class ASN1Util { /** * 将ASN.1格式数据编码为字节数组 * * @param data 编码前的数据 * @return 编码后的数据 * @throws IOException */ public static byte[] encode(byte[] data) throws IOException { // 构造ASN.1格式数据 DERSequence seq = new DERSequence(new ASN1Primitive[]{ new DERInteger(123), new DEROctetString(data) }); // 将ASN.1格式数据编码为字节数组 ByteArrayOutputStream baos = new ByteArrayOutputStream(); ASN1OutputStream os = new ASN1OutputStream(baos); os.writeObject(seq); os.close(); return baos.toByteArray(); } /** * 将字节数组解码为ASN.1格式数据 * * @param encodedData 编码后的数据 * @return 解码后的数据 * @throws IOException */ public static byte[] decode(byte[] encodedData) throws IOException { // 将字节数组解码为ASN.1格式数据 ByteArrayInputStream bais = new ByteArrayInputStream(encodedData); ASN1InputStream is = new ASN1InputStream(bais); DERSequence seq = (DERSequence) is.readObject(); is.close(); // 解析ASN.1格式数据 int intValue = ((DERInteger) seq.getObjectAt(0)).getValue().intValue(); byte[] data = ((DEROctetString) seq.getObjectAt(1)).getOctets(); return data; } } ``` 上述代码中,ASN1Util类提供了encode和decode方法,分别用于将ASN.1格式数据编码为字节数组和将字节数组解码为ASN.1格式数据。在encode方法中,首先构造了一个ASN.1格式的序列,包含一个整数和一个字节数组,然后使用ASN1OutputStream将序列编码为字节数组;在decode方法中,首先使用ASN1InputStream将字节数组解码为ASN.1格式数据,然后解析ASN.1格式数据,获取整数和字节数组。 使用示例: ```java byte[] data = "hello, world!".getBytes(); byte[] encodedData = ASN1Util.encode(data); byte[] decodedData = ASN1Util.decode(encodedData); System.out.println(new String(decodedData)); // 输出:hello, world! ``` 这样,就可以使用Bouncy Castle库在Android上实现ASN.1编解码了。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

luffy5459

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值