0

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.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
SomeHowWhite
  • 931
  • 1
  • 6
  • 9

1 Answers1

2

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.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
  • That's exactly what I want, thanks! I am using AES (CBC) to encrypt/decrypt files. As sizes of those files usually range from 100kb to 500mb, what's the block size you think is reasonable? – SomeHowWhite Jul 29 '17 at 17:07
  • 1
    The block size **of AES** is fixed to 16 bytes (128 bits). The choice of the size of the amount of data to download at a time is up to you, but it needs to be a multiple of 16 of course (you could call it "file fragment size" to distinguish it from the AES block size). Don't forget to prefix the IV, CBC *does* require a random IV. With CBC you should be doubly careful of not implementing a padding oracle. – Maarten Bodewes Jul 29 '17 at 17:12