I need to decrypt a AES encrypted file while downloading it.
That means, every time I receive 256 bytes of data, I could decrypt it right away.
The problem is, users may pause the download process, and restore it later. Then, a new CCCryptorRef instance need to be created to continue to decrypt. But the decrypted data is wrong.
Is there any way to perfectly save a CCCryptorRef instance, so I can use it later?
Btw, I am using iOS framework apis.
I am using CCCryptorCreateWithMode()
, CCCryptorUpdate()
,CCCryptorFinal()
for normal AES processes.
Usually you can create a new cipher context (or whatever the name is, e.g. Cryptor
) if you know the mode of operation in which you use the cipher.
For instance for CBC mode you can store the last cipher block (16 bytes) of the ciphertext you just encrypted. Then you can use that as IV for the next cipher context. On the other hand, if you would use CTR mode then you need to store the last counter value and start decrypting with that counter + 1.
That way you don't ever need to store / restore the cipher context; and this is the reason why this functionality isn't present in the API to start with. You can just create a new one in the required state.
More information about modes of operation here.
In case you use CBC: Beware that you get into trouble with the unpadding at the end of the fragments of ciphertext. You only want to perform unpadding when decrypting the last fragment, and when you do, you should be aware of padding oracle attacks.
Using TLS to protect the file contents in transit should be preferred if it is available.