Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 views
in Technique[技术] by (71.8m points)

java - CipherInputStream and CipherOutputStream are not generating files

I have the following code. However the files b.xlsx and c.xlsx are of 0 bytes. Why is CipherOuputSteam not working?

public static void main(String[] args) throws Exception {

    KeyPair keys = KeyPairGenerator.getInstance("RSA").generateKeyPair();
    Cipher cipher = Cipher.getInstance("RSA");

    cipher.init(Cipher.ENCRYPT_MODE, keys.getPublic());

    FileInputStream fis;
    FileOutputStream fos;
    CipherOutputStream  cos;

    fis = new FileInputStream("C:/temp/a.xlsx");
    fos = new FileOutputStream("C:/temp/b.xlsx");

    cos = new CipherOutputStream (fos, cipher);

    byte[] block = new byte[8];
    int i;
    while ((i = fis.read(block)) != -1) {
        cos.write(block, 0, i);
    }
    cos.close();
    fos.close();



    cipher.init(Cipher.DECRYPT_MODE, keys.getPrivate());
    CipherInputStream cis1, cis2;
    fis = new FileInputStream("c:/temp/b.xlsx");
    CipherInputStream cis = new CipherInputStream(fis, cipher);
    fos = new FileOutputStream("c:/temp/c.xlsx");

    while ((i = cis.read(block)) != -1) {
        fos.write(block, 0, i);
    }
    fos.close();
    fis.close();
    cis.close();
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem lies in your usage - which is incorrect and in the implementation of CipherOutputStream which masks a very important exception - IllegalBlockSizeException.

The problem is that you cannot use an RSA key to encrypt data which is longer than the size of the key (which is 128 bytes in your example). you should use a symmetric encryption algorithm for large blocks of data - e.g. AES.

If you want to use asymmetric keys for a reason (safe transmition of data for example) - you can find a good example on this SO answer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...