面试题答案
一键面试实现思路
- 定义白名单:确定允许反序列化的类,并将它们列入白名单。
- 自定义ObjectInputStream:继承
ObjectInputStream
并重写resolveClass
方法,在该方法中检查要反序列化的类是否在白名单内。
关键代码片段
import java.io.*;
import java.util.HashSet;
import java.util.Set;
public class SecureObjectInputStream extends ObjectInputStream {
// 定义白名单
private static final Set<String> WHITELIST = new HashSet<>();
static {
WHITELIST.add("com.example.YourAllowedClass1");
WHITELIST.add("com.example.YourAllowedClass2");
}
public SecureObjectInputStream(InputStream in) throws IOException {
super(in);
}
@Override
protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
String className = desc.getName();
if (!WHITELIST.contains(className)) {
throw new InvalidClassException("Unauthorized deserialization attempt for class: " + className);
}
return super.resolveClass(desc);
}
}
在反序列化时使用自定义的SecureObjectInputStream
:
try (SecureObjectInputStream ois = new SecureObjectInputStream(new FileInputStream("serializedFile"))) {
Object obj = ois.readObject();
// 处理反序列化后的对象
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}