Java序列化敏感字段加密

     在序列化过程中,虚拟机会试图调用对象类里的 writeObject 和 readObject 方法,进行用户自定义的序列化和反序列化,如果没有这样的方法,则默认调用是 ObjectOutputStream 的 defaultWriteObject 方法以及 ObjectInputStream 的 defaultReadObject 方法。用户自定义的 writeObject 和 readObject 方法可以允许用户控制序列化的过程,比如可以在序列化的过程中动态改变序列化的数值。基于这个原理,可以在实际应用中得到使用,用于敏感字段的加密工作。

测试代码如下:

import java.io.*;
import java.io.ObjectInputStream.GetField;
import java.io.ObjectOutputStream.PutField;

public class Student  implements Serializable {
 
    private String password="passwd";
    public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
 

    private void writeObject(ObjectOutputStream out) {
    	try {
    		PutField pf=out.putFields();
    		System.out.println("原密码:" + password);
    		password="newpasswd";//模拟加密过程
    		pf.put("password", password);
    		System.out.println("加密后密码:" + password);
    		out.writeFields();
    	}catch (IOException e) {
            e.printStackTrace();
        }
    }
    private void readObject(ObjectInputStream in) throws Exception {
    	try {
    		GetField gf=in.readFields();
    		Object o=gf.get("password", "");
    		System.out.println("要解密的字符串:" + o.toString());
    		password = "passwd";//模拟解密,需要获得本地的密钥
    		System.out.println("解密后字符串:" + password);
    	}catch (IOException e) {
            e.printStackTrace();
        }
    }
}

加密关键字段代码:

import java.io.*;

public class SerializableDemo {
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		
		Student stu =new Student();
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
		               new File("E:/Student.txt")));
		oos.writeObject(stu);
		System.out.println("Student对象序列化成功!");
		oos.close();
	}
}

解密关键字段代码:

import java.io.*;
public class AnotherProgram {

	public static void main(String[] args) throws IOException, Exception {
		// TODO Auto-generated method stub
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
				new File("E:/Student.txt")));
		Student student = (Student) ois.readObject();
		System.out.println("Student对象反序列化成功!");;

	}
	
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值