The .NET CryptoStream class in C#

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:


RC2 crypt = RC2.Create();

ICryptoTransform transform = crypt.CreateEncryptor();

CryptoStream cs = 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 C#

Reading and decrypting data in C#

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 C#

Writing and encrypting data in C#

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.