Wednesday, February 23, 2011

Csharp Code : A Better Way To Encrypt And Decrypt String

There Are Many Scenarios in .Net C# where You will need this encryption and description
Include the following namespaces(Apart from other mandatory)

using System.Security.Cryptography;
using System.Text;
---------------------------------------------------------------------------------------
public static String encryptor(String originalPassword,string strkey)
{
TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider();
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
DES.Key = md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strkey));
DES.Mode = CipherMode.ECB;
Byte[] byteData = ASCIIEncoding.ASCII.GetBytes(originalPassword);
return Convert.ToBase64String(DES.CreateEncryptor().TransformFinalBlock(byteData, 0,
byteData.Length));
}

public static String Decryptor(String DrcPassword, string strkey)
{
TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider();
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
DES.Key = md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strkey));
DES.Mode = CipherMode.ECB;
Byte[] byteData = Convert.FromBase64String(DrcPassword);
return
ASCIIEncoding.ASCII.GetString(DES.CreateDecryptor().TransformFinalBlock(byteData, 0,
byteData.Length));
}
------------------------------------------------------------------------------------------
You can invoke these methods by

String strGetEncrypted=encryptor("mySecretThing","myMasterkey");
String strGetDecrypted=decryptor("strGetEncrypted","myMasterkey");

This is it..Keep On Automating things.
--------------------------------------