我正在使用AES / CTR / NoPadding加密我的应用程序中下载的文件。加密与下载一起完成。如果在下载过程中互联网不可用,我需要暂停下载并在网络可用时恢复下载。我正在使用 FileOutputStream(mFile,true)将其余数据附加到文件中。问题是我不知道如何正确地添加到 CipherOutputStream 。当前的实现会创建垃圾数据
这是我的加密方法
private void downloadAndEncrypt() throws Exception {
URL url = new URL(mUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
long downloaded = 0;
if(mFile.exists()){
Logger.e("File exists. Resume Download");
downloaded = mFile.length();
connection.setRequestProperty("Range", "bytes=" + (int)downloaded + "-");
}else{
Logger.e("File doesn't exists. Start Download");
}
connection.connect();
int lenghtOfFile = connection.getContentLength();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK && connection.getResponseCode() != HttpURLConnection.HTTP_PARTIAL) {
throw new IOException("server error: " + connection.getResponseCode() + ", " + connection.getResponseMessage());
}
BufferedInputStream inputStream = new BufferedInputStream(connection.getInputStream());
FileOutputStream fileOutputStream;
if (downloaded == 0)
fileOutputStream = new FileOutputStream(mFile);
else
fileOutputStream = new FileOutputStream(mFile, true);
CipherOutputStream cipherOutputStream = new CipherOutputStream(fileOutputStream, mCipher);
byte buffer[] = new byte[1024 * 1024];
int bytesRead;
long total = 0;
while ((bytesRead = inputStream.read(buffer)) != -1) {
total += bytesRead;
publishProgress((int) ((total * 100) / lenghtOfFile));
cipherOutputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
cipherOutputStream.close();
connection.disconnect();
}