【问题标题】:Why is my object stream getting corrupted? StreamCorruptedException为什么我的对象流损坏了?流损坏异常
【发布时间】:2016-01-10 10:31:43
【问题描述】:

当我尝试读取和解密先前已序列化和加密并保存到文件的数组列表时,出现以下错误。我不明白为什么它说数据已损坏。

java.io.StreamCorruptedException: invalid stream header: EFBEACEF
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:806)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:299)
at amnesty.FileHandling.fileOpen(FileHandling.java:65)
at amnesty.ViewCampaignEvents.open(ViewCampaignEvents.java:183)
at amnesty.MainWindow.valueChanged(MainWindow.java:147)
at javax.swing.JTree.fireValueChanged(JTree.java:2926)
at javax.swing.JTree$TreeSelectionRedirector.valueChanged(JTree.java:3387)
at javax.swing.tree.DefaultTreeSelectionModel.fireValueChanged(DefaultTreeSelectionModel.java:635)
at javax.swing.tree.DefaultTreeSelectionModel.notifyPathChange(DefaultTreeSelectionModel.java:1093)
at javax.swing.tree.DefaultTreeSelectionModel.setSelectionPaths(DefaultTreeSelectionModel.java:294)
at javax.swing.tree.DefaultTreeSelectionModel.setSelectionPath(DefaultTreeSelectionModel.java:188)
at javax.swing.JTree.setSelectionPath(JTree.java:1633)
at javax.swing.plaf.basic.BasicTreeUI.selectPathForEvent(BasicTreeUI.java:2393)
at javax.swing.plaf.basic.BasicTreeUI$Handler.handleSelection(BasicTreeUI.java:3609)
at javax.swing.plaf.basic.BasicTreeUI$Handler.mousePressed(BasicTreeUI.java:3548)
at java.awt.Component.processMouseEvent(Component.java:6522)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6290)
at java.awt.Container.processEvent(Container.java:2234)
at java.awt.Component.dispatchEventImpl(Component.java:4881)
at java.awt.Container.dispatchEventImpl(Container.java:2292)
at java.awt.Component.dispatchEvent(Component.java:4703)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4530)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
at java.awt.Container.dispatchEventImpl(Container.java:2278)
at java.awt.Window.dispatchEventImpl(Window.java:2739)
at java.awt.Component.dispatchEvent(Component.java:4703)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:746)
at java.awt.EventQueue.access$400(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:697)
at java.awt.EventQueue$3.run(EventQueue.java:691)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:719)
at java.awt.EventQueue$4.run(EventQueue.java:717)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:716)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

错误发生在下面的fileOpen方法中,fileClose方法是保存文件的方法。

    public static ArrayList<FileHandling> fileOpen(String fileName) {
    ArrayList<FileHandling> recordsArray = new ArrayList<FileHandling>();

    char fileType = getFileType(fileName);

    try {
        String fileContents = "";
        FileReader text = new FileReader(fileName);
        int inByte;

        inByte = text.read();
        while (inByte != -1) {
            fileContents += (char)inByte;
            inByte = text.read();
        } 
        text.close();

        fileContents = SecurityMethods.decrypt(fileContents, getFileType(fileName));

        InputStream fileStream = new ByteArrayInputStream(fileContents.getBytes());

        if (fileStream.available() > 0) {
            ObjectInputStream objStream = new ObjectInputStream(fileStream);    //error occurs on this line
            recordsArray = (ArrayList<FileHandling>) objStream.readObject();
            objStream.close();
        }
        fileStream.close();

    } catch (IOException | ClassNotFoundException e) {
        e.printStackTrace();
    }

    return recordsArray;
}

public static void fileClose(ArrayList<FileHandling> records, String fileName) {
    try {
        OutputStream fileStream = new ByteArrayOutputStream();
        ObjectOutputStream objStream = new ObjectOutputStream(fileStream);

        objStream.writeObject(records);
        objStream.flush();
        fileStream.flush();
        FileOutputStream fileOutputStream = (new FileOutputStream(fileName));
        byte[] plainTextBytes = ((ByteArrayOutputStream)fileStream).toByteArray();
        String plainText = "";

        for (int i = 0; i < plainTextBytes.length; i++) {
            plainText += (char)plainTextBytes[i];
        } 

        fileOutputStream.write(SecurityMethods.encrypt(plainText, getFileType(fileName)).getBytes());
        fileOutputStream.flush();
        fileOutputStream.close();
        fileStream.close();
        objStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

加解密方法如下

public static String encrypt(String plainText, Character fileType) {
    String encryptedString = "";
    if (!isValidFile(fileType))
        throw new IllegalArgumentException("Invalid fileType.");
    else 
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");  
            SecretKeySpec secretKey = new SecretKeySpec(keys.get(fileType), "AES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            encryptedString = Base64.encode(cipher.doFinal((plainText).getBytes()));

        }   catch (Exception e) {
            e.printStackTrace();
        }
    return encryptedString;
}

private static boolean isValidFile(Character type) {
    return (type == CAMPAIGN || type == EVENT || type == TRANSACTION || type == ACCOUNT || type == EXEC || type == PASSWORD);
}

public static String decrypt(String cipherText, Character fileType) {
    String decryptedString = "";

    if (!isValidFile(fileType))
        throw new IllegalArgumentException("Invalid fileType.");
    else 
        try {
            com.sun.org.apache.xml.internal.security.Init.init();
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            SecretKeySpec secretKey = new SecretKeySpec(keys.get(fileType), "AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            decryptedString = new String(cipher.doFinal(Base64.decode(cipherText)));

        }   catch (Exception e) {
            e.printStackTrace();
        }
    return decryptedString;
}

谢谢

【问题讨论】:

  • 您的编码方法提供了一种从字节到字符串的专有方法。您还需要一个自定义方法来返回字节。 String.getBytes()不是吗。

标签: java encryption serialization stream


【解决方案1】:

您正在将records 序列化为ByteArrayOutputStream。结果:二进制数据。

然后您将字节转换为char????你不能那样做。

你应该直接加密byte[],中间不要做任何奇怪的字符串转换。

创建以下两个方法:

class SecurityMethods {
    String encryptBytes(byte[] data, Character fileType)
    byte[] decryptBytes(String cipherText, Character fileType)
}

如果您还需要在其他地方加密/解密字符串,则可以使用以下两种方法包装它们:

String encryptString(String text, Character fileType) {
    return encryptBytes(text.getBytes(StandardCharsets.UTF_8), fileType);
}
String decryptString(String cipherText, Character fileType) {
    return new String(decryptBytes(cipherText, fileType), StandardCharsets.UTF_8);
}

哎呀,您甚至可以创建可重用的帮助器来进行序列化:

String encryptObject(Serializable obj, Character fileType) {
    // serialize here
    return encryptBytes(bytes, fileType);
}
Serializable decryptObject(String cipherText, Character fileType) {
    byte[] bytes = decryptBytes(cipherText, fileType);
    // deserialize here
}

【讨论】:

  • 感谢排序,我现在用字节处理一切。看不到弦。非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-26
  • 2023-01-02
  • 2020-12-09
相关资源
最近更新 更多