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

时间:2014-05-23 13:32:54

标签: java postgresql encryption

我正在通过加密的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
}

加密可以很好地处理文件流,因此它也可以在这里工作。

更新

作为sugested,我链接输出和跳过DB的输入,我得到相同的错误。我删除了与数据库相关的代码,并更新了剩下的代码以保持问题的清洁。

以下是我加密流的代码:

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...
}

1 个答案:

答案 0 :(得分:1)

<强>更新

我再次查看了你的代码,发现你应该只在写完之后立即关闭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,以使代码更具可读性。