Encypting and Decrypting the strings
This following code will be useful to encrypt or decrypt the string values while passing data on querystrings or want to save the data databse in encrypted format.
//Declare constant for encryption.
public static string KEY = "K6u8#m2a";
//use the following namespace
using System.Security.Cryptography;
//Function to Encrypt the string value.
public static string EncryptString(string stringToEncrypt)
{
byte[] key = { };
byte[] IV = { 0x01, 0x12, 0x23, 0x34, 0x45, 0x56, 0x67, 0x78 };
try
{
key = Encoding.UTF8.GetBytes(KEY);
DESCryptoServiceProvider desProvidr = new
DESCryptoServiceProvider();
byte[] inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);
MemoryStream ms = new MemoryStream();
CryptoStream csstreamdata = new CryptoStream(ms,
desProvidr .CreateEncryptor(key, IV), CryptoStreamMode.Write);
csstreamdata .Write(inputByteArray, 0, inputByteArray.Length);
csstreamdata .FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());
}
catch (Exception ex)
{
throw ex;
}
}
//To decrypt the Encrypted value use this function
public static string DecryptString(string stringToDecrypt)
{
byte[] key = { };
byte[] IV = { 0x01, 0x12, 0x23, 0x34, 0x45, 0x56, 0x67, 0x78 };
stringToDecrypt = stringToDecrypt.Replace(" ", "+");
byte[] inputByteArray = new byte[stringToDecrypt.Length];
try
{
key = Encoding.UTF8.GetBytes(KEY);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
inputByteArray = Convert.FromBase64String(stringToDecrypt);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
Encoding encoding = Encoding.UTF8;
return encoding.GetString(ms.ToArray());
}
catch (Exception ex)
{
throw ex;
}
}
//If you want to pass query string in encrypted format use the following.
response.redirect("welcome.aspx?ID="+EncryptString(value));
//To decrypt the value from query string
string ID=DecryptString(Request.QueryString["Id"].ToString());
Same way you can sent encrypted data to store in database also.