Sunday, May 24, 2009

Encrypting QueryStrings with .NET - Part 1

public class Encryption64
{

private byte[] key = { };
private byte[] IV = { 18, 52, 86, 120, 144, 171, 205, 239 };

public string Decrypt(string stringToDecrypt, string sEncryptionKey)
{
byte[] inputByteArray = new byte[stringToDecrypt.Length + 1];
try
{
key = System.Text.Encoding.UTF8.GetBytes(sEncryptionKey.Substring(0, 8));
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();
System.Text.Encoding encoding = System.Text.Encoding.UTF8;
return encoding.GetString(ms.ToArray());
}
catch (Exception e)
{
return e.Message;
}
}

public string Encrypt(string stringToEncrypt, string SEncryptionKey)
{
try
{
key = System.Text.Encoding.UTF8.GetBytes(SEncryptionKey.Substring(0, 8));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());
}
catch (Exception e)
{
return e.Message;
}
}

}


LATER in the Application where you have to send the query string.. Work out this way

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Move")
{
int QStr =Convert.ToInt32(e.CommandArgument.ToString());
string StrQ = encryptQueryString(QStr.ToString());
Response.Redirect("DisplayPage.aspx?CitationID=" + StrQ, false);
}
}

public string encryptQueryString(string strQueryString)
{
Encryption64 oES = new Encryption64();
return oES.Encrypt(strQueryString, "!#$a54?3");
}
And in the Display Page


protected void Page_Load(object sender, EventArgs e)
{
string ali = "";
if (Request.QueryString["CitationID"] != null)
{
ali = Request.QueryString["CitationID"];
string strdeCrypt = decryptQueryString(ali.Replace(" ", "+"));


}
}

public string decryptQueryString(string strQueryString)
{
Encryption64 oES = new Encryption64();
return oES.Decrypt(strQueryString, "!#$a54?3");
}

No comments: