The CryptoStream wraps an ordinary stream and uses an ICryptoTransform. The CryptoStream have the following key advantages:

– You can use automatic encryption without worrying about the block size required by the algorithm, because the CryptoStream uses buffered access.

– CryptoStream wraps an ordinary .NET stream-derived class and you can easily use it for another operation, such as file access (through a FileStream), memory access (through a MemoryStream), a low-level network call (through a NetworkStream), etc.

You need three parts of information to create a CryptoStream: the underlying stream, the mode (read or write), and the ICryptoTransform you want to use.

You can use the following code to create an ICryptoTransform, based on RC2 algorithm implementation class and then you can use it with an existing stream to create a CryptoStream:

Dim Crypt As RC2 = RC2.Create()

Dim Transform As ICryptoTransform  = Crypt.CreateEncryptor()

Dim Cs As CryptoStream = New CryptoStream(FileStream, Transform, CryptoStreamMode.Write)

‘ (Now you can use Cs to write encrypted information to the file.)


Important notes:

1. The CryptoStream can be in one of two modes: read mode or write mode, as defined by the CryptoStreamMode enumeration. The next picture shows that in read mode, the transformation is performed as it is retrieved from the underlying stream:


Reading and decrypting data in VB.NET

Reading and decrypting data in VB.NET

In write mode mode, the transformation is performed before the data is written to the underlying stream, as shown in the next picture:


Writing and encrypting data in VB.NET

Writing and encrypting data in VB.NET

2. You cannot combine both modes to make a readable and writable CryptoStream.

3. The Seek() method and the Position property of the CryptoStream class, which are used to move to different positions in a stream, are not supported for the CryptoStream and will throw a NotSupportedException if called. However, you can often use these members with the underlying stream.