I'm building a file encryptor/decryptor utility using the .NET Framework 4.5, but when I'm finisched using the CrypyoStream to write to a destination stream, which will write the file to disk or serve as a memory stream to directly read the crypted file, the destination stream happens to be closed
Sub Crypt(ByRef destinationStream As System.IO.Stream) Implements IVersion.Crypt
InitMetadataFromCryptStream()
destinationStream.Write(_fileMetadata.GetBytes(), 0, _fileMetadata.Size)
Using cryptStream As New CryptoStream(destinationStream, encAlgo.CreateEncryptor(), CryptoStreamMode.Write)
_fileStream.CopyTo(cryptStream)
cryptStream.FlushFinalBlock()
End Using
End Sub
The InitMetadataFromCryptStream
basically prepares a custom header for the file, while the encAlgo
is an instance of Rijndael
.
A working solution that I found was to copy the file onto a new MemoryStream
and use it to initialize the CryptoStream
, but it seems a big waste of memory and probably not the best option
As suggested by @Topaco, the fastest way to achieve the leaveOpen parameter logic introduced with the .NET Framework 4.7.2 was to create a new class that inherits the CrypoStream class and dispose only the unmanaged resources
ref. answer: https://stackoverflow.com/a/28057998/6419298