What's the most efficient way to *append* to an encrypted file that preserves the file as a single encrypted stream? RRS feed

  • Question

  • This is a non-trivial problem because:
       1.  You need to efficiently advance the state of the cipher algorithm to the file offset.  A bit like implementing CryptoStream.Seek().

       2.  The cipher may have previously appended block padding at the end of the file.  This mean you can't simply rely on the file length to predict how far to advance the cipher (it is however computable based on cipher block size).


    Tuesday, April 21, 2009 5:57 AM

All replies

  • If you encrypt the data in solid blocks (say, 512 bytes or so), resetting the encyrpter at each block, you can append (or rewrite) any part of the file as long as it's on a block boundary and it matches the block size.  Unfortunately, this significantly compromises the strength of your encryption, as identical data would result in identical blocks.  Normal stream-based encryption uses scrambling techniques so that even repeated data looks different.

    Apart from block-based encryption, your only option is to preserve the state of the encryption stream after the last data is written, and using it to resume later.  None of Microsoft's implementations provide a way to do this, so you'll have to write something custom.  You'd have to be careful how you store the state information because it might be possible to use it to attack already-encrypted data.

    Thursday, April 30, 2009 9:19 PM