在序列化过程中,虚拟机会试图调用对象类里的 writeObject 和 readObject 方法,进行用户自定义的序列化和反序列化,如果没有这样的方法,则默认调用是 ObjectOutputStream 的 defaultWriteObject 方法以及 ObjectInputStream 的 defaultReadObject 方法。用户自定义的 writeObject 和 readObject 方法可以允许用户控制序列化的过程,比如可以在序列化的过程中动态改变序列化的数值。基于这个原理,可以在实际应用中得到使用,用于敏感字段的加密工作。
测试代码如下:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36import 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(); } } }
加密关键字段代码:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12import 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(); } }
解密关键字段代码:
复制代码
1
2
3
4
5
6
7
8
9
10import 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对象反序列化成功!");; } }
最后
以上就是成就乐曲最近收集整理的关于Java序列化敏感字段加密的全部内容,更多相关Java序列化敏感字段加密内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复