This article has been
excerpted from book "The Complete Visual C# Programmer's Guide" from the Authors
of C# Corner.
The System.Security.Cryptography namespace contains support for the most common
symmetric (DES, 3DES, RC2, Rijndael), asymmetric (RSA, DSA), and hash (MD5,
SHA-1, SHA-256, SHA- 384, SHA-512) cryptography algorithms. It also includes a
helpful class to encrypt and decrypt streams. You can use this class, called
CryptoStream, in combination with other stream classes or you can use several
CryptoStream class objects together. With a little effort, you can feed the
output of one CryptoStream object into another CryptoStream object.
Table 22.6 lists the classes and interfaces that are part of the
System.Security.Cryptography namespace of the .NET Framework base class library.
These classes and interfaces define the abstract object model for encryption
algorithms within the .NET Framework. New algorithms may be added to the .NET
Framework by subclassing and/or implementing a portion of these classes and
interfaces.

Table 22.6: Classes and Interfaces in the System.Security.Cryptography
Namespace
Listing 22.35 illustrates the use of DES and CryptoStream classes to encipher
and decipher a file.
Listing 22.35: Cryptostream1.cs, CryptoStream with DES
// NOTE: Before you execute the program, first
// create a file named c:\myfile.txt with text "myname is bozo..." in it.
// After you execute the code, two files will be created on the c: drive.
// The c:\ciphered.txt file will include weird ciphered characters like
// "¼ş_Eó_ğNª_4û Õ?8Ò¤¤_"5"
using System;
using System.IO;
using
System.Security;
using
System.Security.Cryptography;
using System.Text;
class
CryptoDESSample
{
public static
void Main(string[]
args)
{
DESCryptoServiceProvider
ourDESProvider = new
DESCryptoServiceProvider();
// our 8 byte DES secret key is 12345678
ourDESProvider.Key = ASCIIEncoding.ASCII.GetBytes("12345678");
ourDESProvider.IV = ASCIIEncoding.ASCII.GetBytes("12345678");
ICryptoTransform des1 =
ourDESProvider.CreateEncryptor();
ICryptoTransform des2 =
ourDESProvider.CreateDecryptor();
CryptoStream cryptostream1 =
new CryptoStream(fsCiphered,
des1, CryptoStreamMode.Write);
byte[] bytearrayinput =
new byte[fsInput.Length];



Join the conversation! Your thoughts help the community grow.