有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java AES CTR如何附加到CipherOutputStream?

我正在使用AES/CTR/NOPANDING对应用程序中下载的文件进行加密。加密与下载一起完成。当互联网在下载过程中不可用时,我需要暂停下载并在网络可用时恢复它。我正在使用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();
}

共 (0) 个答案