基于对象的编码加密方法

来源:互联网 发布:中电科软件与硬件工资 编辑:程序博客网 时间:2024/04/30 12:11

基于对象的编码加密方法

对象在传输时,需要加密,加密先将对象转化为二进制的字节流,再对流进行加密或编码处理,处理完成后进行传输,接受后解密。传输对象必须实现java.io.Serializable

对象按在内存中变成字节流,需要借助字节输入/输出流来处理。


package test;

 

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.util.Date;

 

import org.apache.xerces.impl.dv.util.Base64;

 

import com.bjnja.core.db.entities.BaseEntity;

 

public class MyObjEncodeTest {

        publicstatic void main(String[] args) throws IOException,

                       ClassNotFoundException{

               // 创建2个对象

               Students1 = new Student("李平",19,1.2345);

               Students2 = new Student("王兵",20,2.3456);

 

               // 创建一个字节输出流,字节流预设为4K

               ByteArrayOutputStreambos = new ByteArrayOutputStream(1024*4);

               // 创建对象输出流,使用字节流进行构造

               ObjectOutputStreamos = new ObjectOutputStream(bos);

               // 写入对象

               os.writeObject(s1);

               os.writeObject(s2);

               // 关闭输出流

               os.close();

               // 从这节输出流中取出字节数组

               bytebin1[] = bos.toByteArray();

               // 关闭输出字节流

               bos.close();

              

               // 对对象流编码,或加密

               Strings = Base64.encode(bin1);

               System.out.println(bos.toByteArray().length);

 

               // 再对上面的数据解码

               bytebin2[] = Base64.decode(s);

               // 创建输入字节流对象,使用解析后的字节流

               ByteArrayInputStreamis = new ByteArrayInputStream(bin2);

               // 创建对象输入流

               ObjectInputStreamois = new ObjectInputStream(is);

               // 从流中读取象1

               Objecto = ois.readObject();

               System.out.println(o.getClass().getName());

               // 输出对象

               System.out.println(o);

 

               // 从流中读取象2

               o =ois.readObject();

               System.out.println(o);

        }

}

 

/*

* 测试使用的对象,对象中包含 串/整数,浮点,和字节对象

*/

class Student implements BaseEntity {

        String name;

        int age;

        double tall;

        Date d = newDate();

 

        Student(Stringn, int a, double t) {

               this.name= n;

               this.age= a;

               this.tall= t;

        }

 

        publicString toString() {

               return"Student {" + name + ";"+ age + "," +tall+","+ d.toString() + "}";

        }

}

 

原创粉丝点击