部分解密文件

时间:2013-09-06 07:08:16

标签: java encryption aes

所以我需要在32位计算机上解密这些大文件(6GB +)。我之前使用的一般过程是读取内存中的整个文件,然后将其传递给decrypt函数,然后将其全部写回文件。由于内存限制,这不起作用。我确实尝试将文件部分传递给decrypt函数,但是在将文件发送到解密函数之前,它似乎弄乱了我打破文件的边界。

我尝试将文件分成相对于密钥大小的部分,但这似乎并不重要。我尝试了一个大小为2048的字节数组以及一个大小为294的字节aray,认为这可能是特殊的边界,但没有运气。我可以看到文件的某些部分被正确解密但部分是完全乱码的。

以块的形式解密文件是不可能的?如果有办法,那怎么办?

这是我的解密功能/我试图解密的部分。

  private Path outFile;

  private void decryptFile(FileInputStream fis, byte[] initVector, byte[] aesKey, long used) {
    //Assume used = 0 for this function. 
    byte[] chunks = new byte[2048]; //If this number is greater than or equal to the size of the file then we are good.
    try {
      if (outFile.toFile().exists())
        outFile.toFile().delete();
      outFile.toFile().createNewFile();
      FileOutputStream fos = new FileOutputStream(outFile.toFile());
      OutputStreamWriter out = new OutputStreamWriter(fos);
      IvParameterSpec spec = new IvParameterSpec(Arrays.copyOfRange(initVector, 0, 16));
      SecretKeySpec key = new SecretKeySpec(aesKey, "AES");
      Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding");
      cipher.init(Cipher.DECRYPT_MODE, key, spec);
      int x;
      while ((x = fis.read(chunks, 0, chunks.length)) != -1) {
        byte[] dec = cipher.doFinal(Arrays.copyOfRange(chunks, 0, x));
        out.append(new String(dec));
      }
      out.close();
      fos.close();
    } catch (Exception e) {
      e.printStackTrace();
      LOG.error(ExceptionUtils.getStackTrace(e));
    }
  }

1 个答案:

答案 0 :(得分:3)

考虑使用Cipher#update(byte[], int, int, byte[], int)代替doFinal()进行多部分操作。这将为您处理部分界限。

可以通过调用doFinal(byte[] output, int outputOffset)方法获得解密数据的最后一部分。