This question already has an answer here:
CipherInputStream and CipherOutputStream are not generating files

(1个答案)


3年前关闭。




我正在尝试使用CipherOutputStream编写加密文件,

PFB序列化代码

public class SerializeDemo implements Serializable{
    private static final long serialVersionUID = -7128734972070518012L;

    private static SerializeDemo INSTANCE = null;

    private ArrayList <SerializeItem> item;
    public static void serialize() {
       INSTANCE = new SerializeDemo();

       ArrayList < SerializeItem > list = new ArrayList < SerializeItem > ();

       SerializeItem item = new SerializeItem();

       item.setV1("DD");
       item.setV2("D");
       list.add(item);

       INSTANCE.setItem(list);
       try {
           Cipher c = Cipher.getInstance("RSA/ECB/PKCS1Padding");
           c.init(Cipher.ENCRYPT_MODE, getKeyPair().getPublic());

           CipherOutputStream cos = new CipherOutputStream(new FileOutputStream("D:\\abc"), c);
           ObjectOutputStream os = new ObjectOutputStream(cos);
           os.writeObject(INSTANCE);
           os.flush();
           os.close();
        } catch (Exception e) {
           e.printStackTrace();
          }

        System.out.println("Serialized");
    }
}


PFB我的SerializeItem类定义

public class SerializeItem implements Serializable{
    private static final long serialVersionUID = 850426811900126363L;

    private String V1 = null;

    private String V2 = null;

//getter setters for the bean file
}


如果我在此类中添加两个以上的String成员变量,则序列化停止,并且我得到一个0字节的文件。请建议

最佳答案

RSA不是分组密码,并且不能像您期望的那样使用CipherOutputStreamclose上的CipherOutputStream方法掩盖了IllegalBlockSizeException,因为数据大于块大小(键大小/ 8-填充),所以会引发该c.doFinal()

如果在关闭前调用,将会看到异常。

09-04 07:44