Wednesday, 15 June 2011

C# - Simple TripleDES Encryption with or without hashing


This class below enables simple encryption and decryption of text strings. It uses the TripleDES algorithms and you can chose weather to use MD5 hash against the key.
Simply change the value of the encryptionKey to whatever you want the key to be.


C# Source code
// <copyright file="EncryptionHelper.cs" company="GinkoSolutions.com">
// Copyright (c) 2011 All Right Reserved
// </copyright>
// <author>Sean Greasley</author>
// <email>sean@ginkosolutions.com</email>
// <summary>Enables simple TripleDES encryption with or without hashing</summary>
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Security.Cryptography;
 
/// <summary>
/// Enables simple TripleDES encryption with or without hashing
/// </summary>
public class EncryptionHelper
{
    /// <summary>
    /// Encryption key. Used to encrypt and decrypt.
    /// </summary>
    private static readonly string encryptionKey = "YOURSECRETKEY";
 
    public EncryptionHelper() {}
 
    /// <summary>
    /// Encrypt text string
    /// </summary>
    /// <param name="toEncrypt">The string of data to encrypt</param>
    /// <param name="useHashing">Weather hashing is used or not</param>
    /// <returns>An encrypted string</returns>
    public static string Encrypt(string toEncrypt, bool useHashing)
    {
        byte[] keyArray;
        byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
 
        // If hashing use get hashcode regards to your key
        if (useHashing)
        {
            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(encryptionKey));
            hashmd5.Clear();
        }
        else
            keyArray = UTF8Encoding.UTF8.GetBytes(encryptionKey);
 
        // Set the secret key for the tripleDES algorithm
        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
        tdes.Key = keyArray;
        tdes.Mode = CipherMode.ECB;
        tdes.Padding = PaddingMode.PKCS7;
 
        // Transform the specified region of bytes array to resultArray
        ICryptoTransform cTransform = tdes.CreateEncryptor();
        byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
        tdes.Clear();
 
        // Return the encrypted data into unreadable string format
        return Convert.ToBase64String(resultArray, 0, resultArray.Length);
    }
 
    /// <summary>
    /// Decrypts a text string
    /// </summary>
    /// <param name="cipherString">The encrypted string</param>
    /// <param name="useHashing">Weather hashing is used or not</param>
    /// <returns>Decrypted text string</returns>
    public static string Decrypt(string cipherString, bool useHashing)
    {
        byte[] keyArray;
        byte[] toEncryptArray = Convert.FromBase64String(cipherString.Replace(' ', '+'));
 
        if (useHashing)
        {
            // If hashing was used get the hash code with regards to your key
            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(encryptionKey));
            hashmd5.Clear();
        }
        else
        {
            // If hashing was not implemented get the byte code of the key
            keyArray = UTF8Encoding.UTF8.GetBytes(encryptionKey);
        }
 
        // Set the secret key for the tripleDES algorithm
        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
        tdes.Key = keyArray;
        tdes.Mode = CipherMode.ECB;
        tdes.Padding = PaddingMode.PKCS7;
 
        ICryptoTransform cTransform = tdes.CreateDecryptor();
        byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
        tdes.Clear();
 
        // Return the Clear decrypted TEXT
        return UTF8Encoding.UTF8.GetString(resultArray);
    }
}

3 comments:

Gabe Co Hadwin said...

Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai. or learn thru Dot Net Training in Chennai. Nowadays Dot Net has tons of job opportunities on various vertical industry.
or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.

simbu said...

This is an awesome post.Really very informative and creative contents. These concept is a good way to enhance the knowledge.I like it and help me to development very well.Thank you for this brief explanation and very nice information.Well, got a good knowledge.
Java training in Chennai

Java training in Bangalore

sathish said...

I appreciate that you produced this wonderful article to help us get more knowledge about this topic.
I know, it is not an easy task to write such a big article in one day, I've tried that and I've failed. But, here you are, trying the big task and finishing it off and getting good comments and ratings. That is one hell of a job done!


Selenium training in bangalore
Selenium training in Chennai
Selenium training in Bangalore
Selenium training in Pune
Selenium Online training