gpt4 book ai didi

java - 为什么反序列化加密对象时会出现 EOFException?

转载 作者:行者123 更新时间:2023-11-29 13:30:53 24 4
gpt4 key购买 nike

我正在通过加密的 ByteArrayOutputStream 将一个序列化和加密的对象写入数据库到一个大对象中。我可以检索这个大对象,但无法反序列化它。

这是我编写的代码:

public void addMessages(int ID, List<Message> messages) {

ObjectOutput output = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ByteArrayInputStream bais = null;
output = new ObjectOutputStream(CryptoHandler.encryptedStream(baos));
output.writeObject(messages);
bais = new ByteArrayInputStream(baos.toByteArray());
output.close();
baos.close();
getMessages(ID, bais);
}

这里是为了阅读:

public List<Message> getMessages(int ID, ByteArrayInputStream bais) {

List<Message> messages = new ArrayList<>();
ObjectInput oi = CryptoHandler.decryptedObjectStream(bais);
messages = (List<Message>) oi.readObject(); //here is where i get the EOFException
}

加密适用于文件流,因此从理论上讲它也应该适用于此。

更新:

如前所述,我跳过数据库链接了输出和输入,但我得到了同样的错误。我删除了与数据库相关的代码并更新了剩余的代码以保持问题干净。

这是我加密流的代码:

public static CipherOutputStream encryptedStream(OutputStream out) {
try {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
return new CipherOutputStream(out, pbeCipher);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(CryptoHandler.class.getName()).log(Level.SEVERE, null, ex);
}//Much more catches here...
}
public static ObjectInputStream decryptedObjectStream(InputStream in) {
try {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
return new ObjectInputStream(new CipherInputStream(in, pbeCipher));
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(CryptoHandler.class.getName()).log(Level.SEVERE, null, ex);
} //Much more catches here...
}

最佳答案

更新

我又看了你的代码,发现,你应该只在写完之后立即关闭 ObjectOutputStream:

public void addMessages(int ID, List<Message> messages) {

ObjectOutput output = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ByteArrayInputStream bais = null;
output = new ObjectOutputStream(CryptoHandler.encryptedStream(baos));
output.writeObject(messages);
output.close(); // it shouldn't remain open after writing the object
bais = new ByteArrayInputStream(baos.toByteArray());
getMessages(ID, bais);
}

但我还建议您将 baos.toByteArray() 保存到 byte[] 中,而不是将 ByteArrayInputStream 作为参数。您应该改为传递字节数组并在 getMessages 函数中创建 ByteArrayInputStream 以使代码更具可读性。

关于java - 为什么反序列化加密对象时会出现 EOFException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23830650/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com