java 对象序列化本身不提供加密,保护数据需要结合 cipheroutputstream 对序列化流进行包装。具体做法是先生成或获取一个对称密钥(如 aes),然后用该密钥初始化 cipher,将 cipheroutputstream 包裹在 objectoutputstream 外层写入文件,读取时反向操作即可实现数据的加密存储与传输。

如何生成用于序列化的加密密钥
使用 AES 算法需要一个有效的 SecretKey。可以通过 KeyGenerator 随机生成密钥,或者从密码派生密钥。生成的密钥必须安全保存,因为解密时需要它。

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.NoSuchAlgorithmException;
public class KeyGen {
public static void main(String[] args) throws NoSuchAlgorithmException {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(128);
SecretKey secretKey = keyGen.generateKey();
System.out.println("Generated Key: " + javax.xml.bind.DatatypeConverter.printHexBinary(secretKey.getEncoded()));
}
}
运行上述代码会输出一个十六进制格式的密钥字符串。在实际应用中,这个密钥应该存储在安全的密钥库中,而不是硬编码在代码里。对于序列化场景,通常使用固定的测试密钥或从配置文件中加载的密钥。
如何实现加密后的对象序列化与反序列化
核心逻辑是将 CipherOutputStream 作为 ObjectOutputStream 的输出目标。写入时,对象先被序列化,然后立即被加密流处理并写入底层字节流。读取时,则相反:先从底层读取字节,通过 CipherInputStream 解密,再交给 ObjectInputStream 还原对象。

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.util.Arrays;
public class SecureSerialization {
private static final String ALGORITHM = "AES";
public static byte[] serialize(Object obj, byte[] key) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
SecretKeySpec keySpec = new SecretKeySpec(key, ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (CipherOutputStream cos = new CipherOutputStream(baos, cipher);
ObjectOutputStream oos = new ObjectOutputStream(cos)) {
oos.writeObject(obj);
}
return baos.toByteArray();
}
public static Object deserialize(byte[] encryptedData, byte[] key) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
SecretKeySpec keySpec = new SecretKeySpec(key, ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, keySpec);
ByteArrayInputStream bais = new ByteArrayInputStream(encryptedData);
try (CipherInputStream cis = new CipherInputStream(bais, cipher);
ObjectInputStream ois = new ObjectInputStream(cis)) {
return ois.readObject();
}
}
public static void main(String[] args) throws Exception {
byte[] key = Arrays.copyOf("0123456789abcdef".getBytes(), 16);
String data = "Sensitive Data";
byte[] encrypted = serialize(data, key);
System.out.println("Encrypted Length: " + encrypted.length);
Object restored = deserialize(encrypted, key);
System.out.println("Restored Data: " + restored);
}
}
这段代码展示了完整的流程。注意 try-with-resources 的使用确保了流和加密状态的正确关闭。如果密钥不匹配或数据被篡改,CipherInputStream 会在读取时抛出 BadPaddingException 或 IllegalBlockSizeException,从而防止解密出损坏的对象。
序列化加密后如何处理版本兼容性问题
当类结构发生变化(如添加字段)时,标准的 Serializable 接口可能因 serialVersionUID 不匹配而拒绝反序列化。在加密场景下,由于数据是密文,无法直接检查元数据,因此必须在解密前确保类的兼容性。最佳实践是在类定义中显式声明 private static final long serialVersionUID,并在修改类时保持其不变,或者在升级时手动更新该值并记录变更。
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
// Getters and Setters
public String getName() { return name; }
public int getAge() { return age; }
}
如果在加密存储期间更新了类版本,旧版本的密文将无法被新版本代码解密还原,除非同时迁移密钥或数据格式。因此,建议在应用升级时,先解密所有旧数据,重新序列化并加密为新格式,再删除旧数据,以确保一致性。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











