Introduction
In web applications it is quite common to send values using QuerySting for instance displaying records as hyperlinks and on click it redirects to new page with mode information about the record. This requires passing unique information about the record like database IDs, primary/foreign key values, etc. in plain text which makes the web application vulnerable to attackers.
It is advised to name the QueryString
property with irrelevant name rather than saying for example EmpID, which makes attacker understand that we are passing Employee ID. And encrypt the value while sending and decrypt it at receiving page will make it difficult for attackers.
The below are two reusable methods that can be used
to encrypt data before sending via QueryString and decrypt upon
reception in the target page.
Using the code
Add the following code in in some common CS file like Util.cs:
using System.Web.Security;
using System.Security.Cryptography;
TripleDESCryptoServiceProvider cryptDES3 = new TripleDESCryptoServiceProvider();
MD5CryptoServiceProvider cryptMD5Hash = new MD5CryptoServiceProvider();
string key = "SomeKeyValue";
public static string Encrypt(string text)
{
cryptDES3.Key = cryptMD5Hash.ComputeHash(ASCIIEncoding.ASCII.GetBytes(key));
cryptDES3.Mode = CipherMode.ECB;
ICryptoTransform desdencrypt = cryptDES3.CreateEncryptor();
byte[] buff = ASCIIEncoding.ASCII.GetBytes(text);
string Encrypt = Convert.ToBase64String(desdencrypt.TransformFinalBlock(buff, 0, buff.Length));
Encrypt = Encrypt.Replace("+", "!");
return Encrypt;
}
public static string Decypt(string text)
{
text = text.Replace("!", "+");
byte[] buf = new byte[text.Length];
cryptDES3.Key = cryptMD5Hash.ComputeHash(ASCIIEncoding.ASCII.GetBytes(key));
cryptDES3.Mode = CipherMode.ECB;
ICryptoTransform desdencrypt = cryptDES3.CreateDecryptor();
buf = Convert.FromBase64String(text);
string Decrypt = ASCIIEncoding.ASCII.GetString(desdencrypt.TransformFinalBlock(buf, 0, buf.Length));
return Decrypt;
}