Pages

Wednesday, July 1, 2009

Code encryption and decryption using a Key in C#

Many time we need to encrypt the user name and password for a high level of security..

here is the code for doing so.. We just need to include the name space System.Security in our application.. IN this code. we can use the Key to encrypt and Decrypt, thus it will provide a higher level of security.. That key we can also save in the Web config file or can provide from front end..

here is the code.


#region "Encryption & Decryption"

public static string Encrypt(string toEncrypt, bool useHashing)
{
byte[] keyArray;
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
string key = "543z";

if (useHashing)
{
MD5CryptoServiceProvider hashmd5
= new MD5CryptoServiceProvider();
keyArray
= hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
hashmd5.
Clear();
}
else
keyArray
= UTF8Encoding.UTF8.GetBytes(key);

TripleDESCryptoServiceProvider tdes
= new TripleDESCryptoServiceProvider();
tdes.
Key = keyArray;
tdes.
Mode = CipherMode.ECB;
tdes.
Padding = PaddingMode.PKCS7;

ICryptoTransform cTransform
= tdes.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
tdes.
Clear();
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}

public static string Decrypt(string cipherString, bool useHashing)
{
byte[] keyArray;
byte[] toEncryptArray = Convert.FromBase64String(cipherString);
string key = "543z";

if (useHashing)
{
MD5CryptoServiceProvider hashmd5
= new MD5CryptoServiceProvider();
keyArray
= hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
hashmd5.
Clear();
}
else
keyArray
= UTF8Encoding.UTF8.GetBytes(key);

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 UTF8Encoding.UTF8.GetString(resultArray);
}

#endregion




Thanks
Anil Kumar Pandey
System Architect
Green Point Technology (India) Ltd.
Mumbai, Maharshtra
INDIA

2 comments:

  1. Hello Anil,

    Nice article. keep it on buddy!

    Regards
    Chetankumar Akarte
    http://www.tipsntracks.com

    ReplyDelete

Kontera