Thursday, July 2, 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(stringtoEncrypt, bool useHashing)
{
byte[] keyArray;
byte[] toEncryptArray =UTF8Encoding.UTF8.GetBytes(toEncrypt);
string key = "543z";

if (useHashing)
{
MD5CryptoServiceProvider hashmd5 = newMD5CryptoServiceProvider();
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();
returnConvert.ToBase64String(resultArray, 0, resultArray.Length);
}

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

if (useHashing)
{
MD5CryptoServiceProvider hashmd5 = newMD5CryptoServiceProvider();
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();
returnUTF8Encoding.UTF8.GetString(resultArray);
}

#endregion

No comments: