0

我正在加密和解密我的應用程序中的文件,但如果文件太大,需要幾分鐘時間,是否有可能提高速度?這是加密/解密代碼如何提高大文件加密/解密的性能

private static void startCrypting(int cipherMode, String key, File inputFile, 
          File outputFile) throws MediaCodec.CryptoException { 
    try { 
     Key secretKey = new SecretKeySpec(key.getBytes(), "AES"); 
     Cipher cipher = Cipher.getInstance("AES"); 
     cipher.init(cipherMode, secretKey); 

     FileInputStream inputStream = new FileInputStream(inputFile); 
     FileOutputStream outputStream = new FileOutputStream(outputFile); 

     CipherOutputStream out = new CipherOutputStream(outputStream, cipher); 
     byte[] buffer = new byte[8192]; 
     int count; 
     while ((count = inputStream.read(buffer)) > 0) { 
      out.write(buffer, 0, count); 
     } 

     out.flush(); 
     out.close(); 
     outputStream.close(); 
     inputStream.close(); 

    } catch (NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException | IOException ex) { 
     ex.printStackTrace(); 
    } 
} 
+0

我不認爲你可以做得更好。如果這需要幾分鐘,該文件必須非常大。 – Henry

+0

如果在這裏安全性不是很大,那麼你可以使用DES算法對稱密鑰。它與AES相比較弱,但會提高性能。 – vijayinani

+2

一般建議:**始終使用完全合格的密碼字符串**'Cipher.getInstance(「AES」);'可能會導致不同的密碼,具體取決於默認安全提供程序。它很可能會導致''AES/ECB/PKCS5Padding'',但它不一定是。如果它改變,你將失去不同JVM之間的兼容性。僅供參考:[Java默認加密/ AES行爲](http://stackoverflow.com/q/6258047/1816580) –

回答

1

很簡單。在適當時加密時,在FileInputStreamCipherInputStream之間加上BufferedInputStream,或在CipherOutputStreamFileOutputStream之間的BufferedOutputStream。這將使文件的I/O一次調整爲8192字節,而不是密碼流可能執行的任何操作。

緩衝流的緩衝區大小並不重要:默認情況下爲8192,並且增加緩衝區的大小並沒有什麼壞處。

你也可以增加你自己的緩衝區的大小。