Use SymmetricAlgorithm to Encrypt and Decrypt Streams

I always was using DESCryptoServiceProvider and TripleDESCryptoServiceProvider classes regardless of their common property and method names but as they're not inherited directly from a same base class, ignored these common names.

SymmetricAlgorithm

Yesterday I came up with a class to encrypt and decrypt my streams which is named SymmetricAlgorithm and is actually the base class for DES and TripleDES classes.  Now this base class is a better choice for me for cryptography.

This class is the base class for symmetric cryptographic algorithms in .NET.  So whether you're using a pre-defined cryptography system in .NET or your own, can try it.  There are four pre-defined symmetric cryptographic systems in .NET which are derived from this base class: DESCryptoServiceProvider, TripleDESCryptoServiceProvider, RC2CryptoServiceProvider and RijndaelCryptoServiceProvider.

Using SymmetricAlgorithm base class you can encrypt and decrypt your streams on basis of all above algorithms and any symmetric algorithm that you implement.

As all symmetric algorithms use a secret key and initialization vector, this base class provides to properties (Key and IV) and appropriate methods to generate them (GenerateKey and GenerateIV).

Process of encryption and decryption is easy.  First you create a SymmetricAlgorithm object by calling Create() static method of SymmetricAlgorithm class and passing string value of an algorithm name.  After this, you use CreateEncryptor() and CreateDecryptor() methods of SymmetricAlgorithm class to create an ICryptoTransform object then use this ICryptoTransform object to pass to constructor of a CryptoStream object (which will be configured for encryption and decryption by passing other appropriate parameters) to encrypt or decrypt streams.

It's worth to take a look at an example.  Later you'll see an example of SymmetricAlgorithm object.  It is a Console Application and gets the path of a file then generates four encrypted files and four corresponding decrypted files from them in same folder by using four different symmetric algorithms: DES, TripleDES, RC2 and Rijndael.

Below is the main body of Console Application which creates SymmetricAlgorithm object, generates a secret key and initialization vector for each algorithm, constructs file names and calls Encrypt() and Decrypt() methods by passing two parameters to encrypt and decrypt file streams.

static void Main(string[] args)

{

    Console.Title = "Symmetric Algorithms Cryptography";

    Console.WriteLine("Enter File Path:");

    String path = Console.ReadLine();

 

    List<String> algorithms = new List<String>();

    algorithms.Add("DES");

    algorithms.Add("TripleDES");

    algorithms.Add("RC2");

    algorithms.Add("Rijndael");

 

    foreach (String algorithm in algorithms)

    {

        SymmetricAlgorithm symmetricAlgorithm =

            SymmetricAlgorithm.Create(algorithm);

 

        symmetricAlgorithm.GenerateKey();

        symmetricAlgorithm.GenerateIV();

 

        String outPath = Path.GetDirectoryName(path) + @"\" +

            Path.GetFileNameWithoutExtension(path) + "_" + algorithm;

        String encryptedPath = outPath + ".encrypted";

        String decryptedPath = outPath + ".decrypted";

 

        Encrypt(symmetricAlgorithm, path, encryptedPath);

        Decrypt(symmetricAlgorithm, encryptedPath, decryptedPath);

 

        Console.WriteLine(algorithm + " Done!");

    }

    Console.ReadLine();

}

Encrypt and Decrypt methods are very similar.  They both create an ICryptoTransform object and pass it to constructor of a CryptoStream then follow some stream manipulations to encrypt or decrypt streams.

private static void Encrypt(SymmetricAlgorithm symmetricAlgorithm,

    String inPath, String outPath)

{

    FileStream outStream = File.OpenWrite(outPath);

 

    ICryptoTransform transform = symmetricAlgorithm.CreateEncryptor();

 

    CryptoStream cryptoStream =

        new CryptoStream(outStream, transform, CryptoStreamMode.Write);

 

    Byte[] inFile = File.ReadAllBytes(inPath);

 

    cryptoStream.Write(inFile, 0, inFile.Length);

    cryptoStream.Close();

}

 

private static void Decrypt(SymmetricAlgorithm symmetricAlgorithm,

    String inPath, String outPath)

{

    ICryptoTransform transform = symmetricAlgorithm.CreateDecryptor();

 

    Stream inStream = File.OpenRead(inPath);

    CryptoStream cryptoStream =

        new CryptoStream(inStream, transform, CryptoStreamMode.Read);

 

    Byte[] buffer = new Byte[50];

 

    int length = cryptoStream.Read(buffer, 0, buffer.Length);

 

    Stream outStream = File.OpenWrite(outPath);

    while (length > 0)

    {

        outStream.Write(buffer, 0, length);

        length = cryptoStream.Read(buffer, 0, buffer.Length);

    }

    inStream.Close();

    outStream.Close();

}

Now playing: Chris De Burgh - Living In The World

[advertisement] Axosoft OnTime 2008 is four developer tools in one: bug tracking, project wiki, feature management, and help desk. It manages your development process so developers can focus on coding. Installed or Hosted – Free Single-user license -- Free 30-day team trial.

No Comments : 11.10.06

Feedbacks

There are no comments yet...Kick things off by filling out the form below.

Leave a Comment