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:
FileStream stream = new FileStream(�C:\\test.txt�,
FileMode.OpenOrCreate,FileAccess.Write);
DESCryptoServiceProvider cryptic = new DESCryptoServiceProvider();
cryptic.Key = ASCIIEncoding.ASCII.GetBytes(�ABCDEFGH�);
cryptic.IV = ASCIIEncoding.ASCII.GetBytes(�ABCDEFGH�);
CryptoStream crStream = new CryptoStream(stream,
cryptic.CreateEncryptor(),CryptoStreamMode.Write);
byte[] data = ASCIIEncoding.ASCII.GetBytes(�Hello World!�);
crStream.Write(data,0,data.Length);
crStream.Close();
stream.Close();
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:
FileStream stream = new FileStream(�C:\\test.txt�,
FileMode.Open,FileAccess.Read);
DESCryptoServiceProvider cryptic = new DESCryptoServiceProvider();
cryptic.Key = ASCIIEncoding.ASCII.GetBytes(�ABCDEFGH�);
cryptic.IV = ASCIIEncoding.ASCII.GetBytes(�ABCDEFGH�);
CryptoStream crStream = new CryptoStream(stream,
cryptic.CreateDecryptor(),CryptoStreamMode.Read);
StreamReader reader = new StreamReader(crStream);
string data = reader.ReadToEnd();
reader.Close();
stream.Close();
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.