如果文件太大而无法将其全部加载到内存中

如果文件太大而无法将其全部加载到内存中

本文介绍了IOS - 如果文件太大而无法将其全部加载到内存中,我如何对大文件进行 AES 解密?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何对 NSData 进行 AES 加密和解密,但这需要先将整个文件加载到内存中.

假设我有一个名为 data.dat.enc 的 50mb 加密文件,我如何将其解密为文件 data.dat 而无需先将其全部加载到内存?

解决方案

此代码已由 http://github.com/rnapier/RNCryptor.

RNCryptManager 是一个很好的例子这个怎么做.来自iOS5:PTL的第11章示例代码.看:

+ (BOOL)decryptFromStream:(NSInputStream *)fromStreamtoStream:(NSOutputStream *)toStream密码:(NSString *)密码错误:(NSError **)错误;

它假定盐和 IV 已预先添加到流中(这在书中都有解释).有关 AES 加密的更一般性讨论,请参阅使用 CommonCrypto 使用 AES 正确加密..p>

有关其使用示例,请参阅 CPCryptController.m 在同一个项目中.

如果有足够的兴趣,我可以把这个对象拉出来,作为一个独立的项目来支持它,而不仅仅是一段示例代码.它似乎对人们相当有用.但按原样集成并不难.

更一般的答案是您使用 CCCryptorCreate 创建一个密码器,然后为每个块调用 CCCryptorUpdate.然后你调用 CCCryptorFinal 来完成.

I know how to AES encrypt and decrypt an NSData, but that requires loading the whole file into memory first.

Say I have a 50mb encrypted file called data.dat.enc, how can I decrypt it to a file data.dat without having to first load it all into memory?

解决方案

EDIT: This code has been expanded by http://github.com/rnapier/RNCryptor.


RNCryptManager is a good example of how to do this. It comes from the Chapter 11 sample code of iOS5:PTL. Look at:

+ (BOOL)decryptFromStream:(NSInputStream *)fromStream
                 toStream:(NSOutputStream *)toStream
                 password:(NSString *)password
                    error:(NSError **)error;

It assumes that the salt and IV have been prepended to the stream (this is all explained in the book). For some more general discussion on AES encryption, see Properly encrypting with AES with CommonCrypto.

For an example of its use, see CPCryptController.m in the same project.

If there's sufficient interest, I could pull this object out and support it as a stand-alone project rather than just as a piece of sample code. It seems reasonably useful to people. But it's not that difficult to integrate as-is.

The more general answer is that you create a cryptor with CCCryptorCreate and then make calls to CCCryptorUpdate for each block. Then you call CCCryptorFinal to finish things up.

这篇关于IOS - 如果文件太大而无法将其全部加载到内存中,我如何对大文件进行 AES 解密?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 15:40