如何使加密代码在较大的文件上工作

时间:2019-04-18 15:55:17

标签: java security encryption rsa

我有Java RSA代码,可以很好地处理小文件,但是当我尝试加密大文件时,大小会出错。

javax.crypto.IllegalBlockSizeException: Data must not be longer than 245 bytes

如何使它加密任何大小的数据?

public void encrypt(PublicKey publicKey, String message, String destPath) throws Exception {
    Cipher cipher = Cipher.getInstance("RSA");  
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);  

    File rawFile = new File(message);
    File encryptedFile = new File(destPath);

    InputStream inStream = new FileInputStream(rawFile);
    OutputStream outStream = new FileOutputStream(encryptedFile);
    byte[] buffer = new byte[1024];
    int len;
    while ((len = inStream.read(buffer)) > 0) {
        outStream.write(cipher.update(buffer, 0, len));
        outStream.flush();
    }
    outStream.write(cipher.doFinal());
    inStream.close();
    outStream.close();
}


public void decrypt(PrivateKey privateKey, String encrepted, String decrptPath) throws Exception {
    Cipher cipher = Cipher.getInstance("RSA");  
    cipher.init(Cipher.DECRYPT_MODE, privateKey);

    File encryptedFile = new File(encrepted);
    File decryptedFile = new File(decrptPath);

    InputStream inStream = new FileInputStream(encryptedFile);
    OutputStream outStream = new FileOutputStream(decryptedFile);
    byte[] buffer = new byte[1024];
    int len;
    while ((len = inStream.read(buffer)) > 0) {
        outStream.write(cipher.update(buffer, 0, len));
        outStream.flush();
    }
    outStream.write(cipher.doFinal());
    inStream.close();
    outStream.close();
}

0 个答案:

没有答案