Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IOS - How do I AES decrypt a large file if the file is too large to load all of it into memory?

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?

like image 814
Kyle Avatar asked Mar 15 '12 17:03

Kyle


1 Answers

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.

like image 177
Rob Napier Avatar answered Sep 21 '22 16:09

Rob Napier