Ari Seyhun
Ari Seyhun

Reputation: 12521

Encrypting Files with AES C# in Chunks

I'm trying to encrypt and decrypt a file in chunks in C# with AES encryption.

Currently, it reads a file in chunks of 1000 bytes, encrypts each chunk, and writes over the file with the format of {IV}{Chunk0}{Chunk1}{Chunk2}... (without any separation characters and no curly braces).

When decrypting the file, it reads the first 16 bytes from the file, uses it as the AES IV and decrypts the rest of the file in chunks.

My problem is, how can I know the size of each encrypted chunk to decrypt? When encrypting, each chunk consists of 1000 bytes of plain text, but when it's encrypted, this length of 1000 changes.

Should I use a separation character between each chunk such as a comma? Or is it possible for me to avoid using a separation character between the chunks and instead decode by reading chunks of x characters? (As stated above, is it possible for me to calculate the size of each encrypted chunk if each one is 1000 bytes of encrypted plain-text?)

Upvotes: 1

Views: 872

Answers (1)

Kevin
Kevin

Reputation: 2243

Simplest? When you encrypt each chunk, get the byte length, and then store it as well in your file:

{IV}{LengthOfEncryptedChunk}{EncryptedChunk}{IV}{LengthOfEncryptedChunk} ... etc

Upvotes: 1

Related Questions