CipherOutputStream创建0字节文件

时间:2017-01-10 08:59:32

标签: java encryption

我正在尝试使用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
}

如果我在这个类序列化中添加了2个以上的String成员变量,那么我将得到一个0字节的文件。请建议

1 个答案:

答案 0 :(得分:1)

RSA不是分组密码,并且不会像您期望的那样使用CipherOutputStreamclose上的CipherOutputStream方法屏蔽IllegalBlockSizeException,因为您的数据长于块大小(keysize / 8 - padding),所以会引发c.doFinal()

如果您在结束前致电SELECT p.*, group_concat(atts.name) FROM products as p LEFT JOIN attributes as atts ON p.product_id = atts.product_id Group BY /*all columns not included in aggregate (noc necc for mysql but other dbs like mssql get crazy about that*/ ,您将看到异常。