I'd like to append data to an already encrypted file (AES, CBC-Mode, padding PKCS#7) using CryptoStream without reading and writing the whole file.
Example:
Old Content: "Hello world..."
New Content: "Hello world, with appended text"
Of course I would have to read individual blocks of data and append then to a already present block. In the above mentioned example I would have to read the number of bytes present in the first block (14 bytes) and append two bytes to the first block, then writing the rest of the appended text
"Hello world, wi"
"th appended text"
One problem I am facing is that I am unable to read the number of bytes in a data block. Is there a way to find out the number of bytes present (in the example, 14)?
Additionally I am stuck since the CryptoStreamMode only has members for Read and Write, but no Update.
Is there a way to accomplish my desired functionality using CryptoStream?
It is a little complex, but not too much. Note that this is for CBC mode + PKCS#7!
Three methods:
WriteStringToFile
will create a new file,AppendStringToFile
will append to an already encrypted file (works asWriteStringToFile
if the file is missing/empty),ReadStringFromFile
will read from the file.Example of use:
How does the
AppendStringToFile
works? Three cases:WriteStringToFile
plainText
plainText
. To reencyrpt the last block, the IV used is the penultimate block.