Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Encrypt and Decrypt data

3.40/5 (3 votes)
12 Aug 2013CPOL 27.8K  
Encrypt data before sending via QueryString and decrypt upon reception in the target page.

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:
C#
//Namespace
using System.Web.Security;
using System.Security.Cryptography;
//Declare the below
TripleDESCryptoServiceProvider cryptDES3 = new TripleDESCryptoServiceProvider();
MD5CryptoServiceProvider cryptMD5Hash = new MD5CryptoServiceProvider();
string key = "SomeKeyValue";
C#
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;
} 
C#
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;
} 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)