Cipher.dofinal出现内存不足错误()

问题描述:

我正在开发Android应用程序,我正在使用Android的密码类对进行解密。Cipher.dofinal出现内存不足错误()

代码:

private byte[] decrypt_chunk(byte[] data, ByteString chunk_encryption_key) { 
     SecretKeySpec skeySpec = new SecretKeySpec(chunk_encryption_key.toByteArray(), 1, 16, "AES"); 
     Cipher cipher; 
     byte[] decrypted = new byte[0]; 
     try { 
      cipher = Cipher.getInstance("AES/CFB/NoPadding"); 

      cipher.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(getIV(0))); 

      decrypted = cipher.doFinal(data); 

     } catch (NoSuchAlgorithmException | NoSuchPaddingException e) { 
      e.printStackTrace(); 
     } catch (InvalidKeyException e) { 
      e.printStackTrace(); 
     } catch (InvalidAlgorithmParameterException e) { 
      e.printStackTrace(); 
     } catch (ShortBufferException e) { 
      e.printStackTrace(); 
     } 

     return decrypted; 
    } 

我得到“内存不足”错误,而解密大文件。

我有以下问题:

  1. 在当前的代码是什么chanegs可以修复OOM错误

  2. Cipher.update()可以帮助解决这个问题?如果是的话,如何实施呢?

谢谢。

+0

如何加载数据? –

+0

我正在从在线服务器读取数据并将其存储在byte []中。 –

+0

您无法一次加载整个文件。您需要一次加载块。 –

使用Cipher.update()方法是一种可能的方法。

但在你的情况下,我建议你使用CipherOutputStream来代替。我假设你有一个用于从服务器获取数据的InputStream和一个用于将数据保存到文件中的FileOutputStream。

使用CipherOutputStream是非常简单的,只是“总结为”绕FileOutputStream中:

FileOutputStream fout = ... 
CipherOutputStream cout = new CipherOutputStream(fout, cipher); 

现在继续使用cout而不是fout和你写进去一切都将被自动加密。

+0

谢谢你的回答。但是我需要在从服务器读取字节的同时执行一些操作,因此我将数据存储为byte []。 –

+0

或者您使用'ChipherInputStream'代替(读取时加密/解密)。它以相同的方式工作,但包装一个InputStream,就像从Web加载文件时获得的那样。 – Robert