How to solve the security problem of default serialization in Java?

The default serialization in Java has some security problems. For example, the bytes after object serialization are transmitted through the network, and may be intercepted on the network. How to ensure data security? Usually, the object content can be encrypted when the object is serialized, and decrypted when the object is deserialized.

Specific realization process analysis:

  1. Add the writeObject(ObjectOutpuStream out) method to the serialized object to encrypt the content and then perform serialization.
  2. Add the readObject(ObjectInputStream in) method to the serialized object to deserialize the content and then perform the decryption operation

Code:

class SysLog implements Serializable{
	private static final long serialVersionUID = -5296788134693797316L;
	/**日志id*/
	private Integer id;
	/**操作用户*/
	private String username;
	//private Date createdTime;
	
	/**此方法会在调用对象流的的writeObject方法时执行*/
	private void writeObject(ObjectOutputStream out) throws IOException{
		//1.获取一个加密对象(java.util)
		Base64.Encoder encoder=Base64.getEncoder();
		//2.对内容进行加密
		byte[] array=encoder.encode(username.getBytes());
		//3.将加密结果重新赋值给username
		username=new String(array);
		//4.执行默认序列化
		out.defaultWriteObject();//序列化
	}//方法的声明是一种规范
	
	private void readObject(ObjectInputStream in)
		throws IOException, ClassNotFoundException{
		//1.执行默认反序列化
		in.defaultReadObject();
		//2.获取解密对象
		Base64.Decoder decoder=Base64.getDecoder();
		//3.执行解密操作
		byte[] array=decoder.decode(username);
		username=new String(array);
	}
	
	public void setId(Integer id) {
		this.id = id;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	@Override
	public String toString() {
		return "SysLog [id=" + id + ", username=" + username + "]";
	}
}

Description: writeObject/readObject method:

  1. The access modifier, return value type, method name, and parameters should be the same as the above code (defined in the java specification)
  2. The two methods will be called by the bottom layer of the system through reflection during serialization and deserialization .

Guess you like

Origin blog.csdn.net/qianzhitu/article/details/103002673