我正在加密和解密我的应用程序中的文件,但如果文件太大需要几分钟,是否可以提高速度?这是加密/解密代码
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 :(得分:1)
简单。在BufferedInputStream
和FileInputStream
解密之间添加CipherInputStream
,或在加密时BufferedOutputStream
和CipherOutputStream
之间添加FileOutputStream
,视情况而定。这将使文件的I / O一次性调整为8192个字节,而不是密码流可能做的任何事情。
缓冲流的缓冲区大小并不重要:默认情况下它是8192,并且增加它没有任何害处。
您还可以增加自己缓冲区的大小。