Using CryptoStream in C#

This article explains how to use CryptoStream for simple on the fly cryptography.

Introduction

Encryption in C# is a lot easier using the standard components provided by the .NET framework. In this article, I will explain how it works.

.NET provides us with a standard set of cryptography providers. These are samples of standard cryptography providers:

Rijndael

RSA

DES

DSA

TripleDES

These cryptography providers can be used in combination with the CryptoStream class. This class can encrypt/decrypt data on the fly from an underlying stream. You can link up almost any stream to the CryptoStream, as long as it supports the standard stream functionality defined in the Stream base class.

How to use CryptoStream

It’s pretty straightforward. First, you need a base stream which you will use as buffer for the encryption/decryption. You also need a cryptographic transformer which is part of the CryptographicServiceProvider class. If you combine these parts into a CryptoStream, you can encrypt/decrypt on the fly.

The following example explains best how the whole process of encryption works:

The key and the initialization vector must be 8 characters long, that is 64 bits. This is because the DES cryptography provider uses a 64 bit key to encrypt data. If you use other algorithms for your CryptoStream, you will probably need another key size. Check the documentation on how large the key and the IV must be.

We could also decrypt data using CryptoStream. The following example shows how to decrypt data from a file:

Conclusion

The cryptography services in .NET are pretty simple and work very well. And I hope this article has contributed to a better knowledge about cryptography and how to use it in .NET.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

The key and initialization vector are a bit short now, I think you need at least 16 bytes to create a combination for an 128 algorithm.
My advice is to check the MSDN documentation on the key size required.

WM.What about weapons of mass-construction?"What? Its an Apple MacBook Pro. They are sexy!" - Paul WatsonMy blog