Adnan’s Blog

Encypting query string in asp.net

Posted on: July 8, 2008

When you pass information from one page to another, you are passing information that anybody can sniff. For example consider a scenario, in which you pass the customer id as a query string:

http://www.yourapplication.com?customer_id=15

Now if somebody replaced 15 with say 10 or any other number, they can pull up other customer information. And thats a bad for security.

One solution to this problem is to use ecryption using a secret key. So lets use a hard-to-crack 8 byte key like $zm0!qp?

To accomplish this heres a code snippet


using System;
using System.IO;
using System.Xml;
using System.Text;
using System.Security.Cryptography;

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, 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, 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;
}
}
}

The end user will get to see a random text in the query string, something like

http://www.yourapplication.com/Receive.aspx?key=a2f5ckj?h79#8dd3

Remember stay secure stay safe.

Advertisements

1 Response to "Encypting query string in asp.net"

Great Post, helped me soo mutch

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: