Visual Studio .NET - to secure query string in asp.net with c# 2.0

Asked By praveen sinha on 08-Mar-08 07:15 AM

I am not getting it in c# "Encryption64".Is any namespace or dll is to be imported in c#.Please help me, and give me solutions I need it urgent.


Thanks

First write/copy public custom class shown in below link - manish bafna replied to praveen sinha on 08-Mar-08 07:26 AM

Hi,

If i am not wrong then you are using sample given in below link for encrypting/decrypting querystring.

http://forums.asp.net/t/989552.aspx

Then you need to write below public class and then call Dim oEs As New Encryption64
Imports System
    Imports System.IO
    Imports System.Xml
    Imports System.Text
    Imports System.Security.Cryptography

    Public Class Encryption64
        Private key() As Byte = {}
        Private IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}

        Public Function Decrypt(ByVal stringToDecrypt As String, _
            ByVal sEncryptionKey As String) As String
            Dim
inputByteArray(stringToDecrypt.Length) As Byte
             Try

                key = System.Text.Encoding.UTF8.GetBytes(Left(sEncryptionKey, 8))
                Dim des As New DESCryptoServiceProvider()
                inputByteArray = Convert.FromBase64String(stringToDecrypt)
                Dim ms As New MemoryStream()
                Dim cs As New CryptoStream(ms, des.CreateDecryptor(key, IV), _
                    CryptoStreamMode.Write)
                cs.Write(inputByteArray, 0, inputByteArray.Length)
                cs.FlushFinalBlock()
                Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8
                Return encoding.GetString(ms.ToArray())
            Catch e As Exception
                Return e.Message
            End Try
        End Function

        Public Function
Encrypt(ByVal stringToEncrypt As String, _
            ByVal SEncryptionKey As String) As String
            Try

                key = System.Text.Encoding.UTF8.GetBytes(Left(SEncryptionKey, 8))
                Dim des As New DESCryptoServiceProvider()
                Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes( _
                    stringToEncrypt)
                Dim ms As New MemoryStream()
                Dim cs As New CryptoStream(ms, des.CreateEncryptor(key, IV), _
                    CryptoStreamMode.Write)
                cs.Write(inputByteArray, 0, inputByteArray.Length)
                cs.FlushFinalBlock()
                Return Convert.ToBase64String(ms.ToArray())
            Catch e As Exception
                Return e.Message
            End Try
        End Function

    End Class

check it out - Santhosh N replied to praveen sinha on 08-Mar-08 09:07 AM

 
Once upon a time in the tech world, obscurity was security - this being most true in the early years of the industry, when there were gaping holes in privacy policies and confidential client information was bandied about from site to site without a care as to who actually could read the information. With the new Cryptography classes in .NET, there's absolutely no excuse for not hiding even the most innocuous user data.

Encrypting QueryStrings with .NET

Once upon a time in the tech world, obscurity was security - this being most true in the early years of the industry, when there were gaping holes in privacy policies and confidential client information was bandied about from site to site without a care as to who actually could read the information.

With the new Cryptography classes in .NET, there's absolutely no excuse for not hiding even the most innocuous user data. If you ever need to 'piggy-back' information from one web page to another, whether it is within a POST or a GET parameter, you're passing clear information that anyone can sniff - and that's a bad thing.

If you're not going to use a session variable for storing end user information, you're most likely going to keep some sort of State by passing the information to a cookie or push it around with GET/POST parameters. If you're passing around any sort of ID or user information like their name, it's better to err on the side of caution and encrypt the information.

GET Vs. POST

A POST parameter keeps the information out of the URL, but it can still be sniffed quite easily as it passes in clear text across your network or the Internet. Using POST will keep the mere curious at bay, as the information is not contained in the URL - but this will not stop someone determined to snag out your data.

A QueryString parameter passes information within the site's URL. Why would you even use a QueryString? Well, maybe you need to let your user bookmark a particular page, or maybe you have to refer directly to a page in a URL via a link - you can't do either if you're using POST. A QueryString puts data in the URL for the entire world to see, so if you don't know if the end user is malicious, I'd think hard about using a QueryString for anything but site-related information.

Be smart and encrypt any and all data you're moving around from page to page, especially if that information could be used maliciously. You may trust your users, but you still need that extra level of security that clear text GET/POST data doesn't provide.

Imagine this scenario - you've been passing the customer's ID in the database around in a QueryString, in a URL that looks like this:

http://yoursite.com?cust_id=29

You know what a user is going to do? Switch that 29 to a 30 or 12 or some other number, and if you're not checking for invalid requests, you'll be dishing up some other customer's data.

Enter Encryption

What I was looking for was a quick way to encrypt and decrypt parts of a QueryString - it had to be on the fly, quick and dirty.

I chose Base64 because it wouldn't throw bizarre characters in my QueryString that I couldn't pass around… Little did I know that I'd hit a snag while passing around my encrypted QueryString - Apparently, the Request.QueryString object interprets the '+' sign as a space! So, with a quick Replace function slapped on my decrypt string, no harm, no foul.

Symmetric Key

The whole trick to this working is that the QueryString is encrypted and decrypted with the same private key. This is the secret key - if anyone gets a hold of your key, they can decrypt the data themselves, so keep it a secret!

We're going to use a hard-to-crack 8 byte key, !#$a54?3, to keep parts of our QueryString secret.

Let's Walk through the C# portion of the code:

Notice our two functions that abstract the dirty work that our Encryption64 class. The first, encryptQueryString, is used to encrypt the value of a QueryString. The second, decryptQueryString, is used to decrypt the value of an encrypted QueryString.

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

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

If we wanted to encrypt our QueryString on our first page, we could do something like this:

string strValues = "search term";
string strURL = "http://yoursite.com?search="
    + encryptQueryString(strValues);
Response.Redirect(strURL);

Inside our code-behind in our second page, we pass the contents our QueryString to a variable named strScramble. After that, we replace the '+' signs that our wonderful Request.QueryString has replaced with a space. We pass that string into our function, decryptQueryString, and retrieve the decrypted string.

string strScramble =  Request.QueryString["search"];
string strdeCrypt = decryptQueryString(
    strScramble.Replace(" ", "+"));

Now we've decrypted the value of the QueryString, 'search', and we can do whatever we want with it. The end user is going to see a URL that looks like:

http://yoursite.com?search=da00992Lo39+343dw

They'll never be able guess what's going on in your QueryString, and if they try to fool around with it, there's no way to crack the code without knowing the Symmetric key.

namespace... - Santhosh N replied to praveen sinha on 08-Mar-08 09:15 AM

Encryption64 class is available System.Security.Cryptography namespace....
Encryption64 class is not found - praveen sinha replied to Santhosh N on 08-Mar-08 09:24 AM
well, is there any dll which i have to include for "Encryption64 class".
Try this out... - Santhosh N replied to praveen sinha on 08-Mar-08 10:27 AM

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Text;

using System.Security.Cryptography;

using System.IO;

using System.Xml;

public partial class EncrytingQueryString_Pag1 : System.Web.UI.Page

{

private byte [] key= { };

private byte[] IV = {10, 20, 30, 40, 50, 60, 70, 80}; // it can be any byte value

protected void Page_Load(object sender, EventArgs e)

{

string m_Id ="1010101023";

string m_Value="Henry is King";

Response.Redirect( "EncrptingQueryString_Page2.aspx?Id="+encryptQueryString(m_Id) );

}

public string encryptQueryString( string strQueryString )

{

// ExtractAndSerialize.Encryption64 oES=

// new ExtractAndSerialize.Encryption64( );

//return oES.Encrypt( strQueryString, "!#$a54?3" );

return Encrypt( strQueryString, "!#$a54?3" );

}

public string decryptQueryString(string strQueryString)

{

// ExtractAndSerialize.Encryption64 oES =

// new ExtractAndSerialize.Encryption64();

// return oES.Decrypt(strQueryString,"!#$a54?3");

return Decrypt(strQueryString,"!#$a54?3");

}



public static string Decrypt( string stringToDecrypt, string sEncryptionKey )

{

byte [] key= { };

byte [] IV= { 10, 20, 30, 40, 50, 60, 70, 80 };

byte [] inputByteArray=new byte [stringToDecrypt.Length];

try

{

key=
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( );

Encoding encoding=Encoding.UTF8;return encoding.GetString( ms.ToArray( ) );

}

catch ( System.Exception ex )

{

throw ex;

}

}

public static string Encrypt( string stringToEncrypt, string sEncryptionKey )

{

byte [] key= { };

byte [] IV= { 10, 20, 30, 40, 50, 60, 70, 80 };

byte [] inputByteArray; //Convert.ToByte(stringToEncrypt.Length)

try

{

key=
Encoding.UTF8.GetBytes( sEncryptionKey.Substring( 0, 8 ) );

DESCryptoServiceProvider des=new DESCryptoServiceProvider( );

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 ( System.Exception ex )

{

throw ex;

}

}
//end of Encrypt

}//end of class


Here is the code  on Page2

protected void Page_Load(object sender, EventArgs e)

{

string m_Id = Request.QueryString["Id"];

m_Id=m_Id.Replace(" ", "+" );Label1.Text="The Id is: " + decryptQueryString( m_Id );

}


public string decryptQueryString( string strQueryString )

{

return Decrypt( strQueryString, "!#$a54?3" );

}

go for URL Rewriting / Mapping in ASP.NET 2.0 - K Pravin Kumar Reddy replied to praveen sinha on 08-Mar-08 12:59 PM

check samples in below links...

for more security encode the querystring parameters....

http://www.developer.com/net/asp/article.php/3581326

http://quickstarts.asp.net/QuickStartv20/aspnet/doc/navigation/urlmapping.aspx

http://www.developer.com/net/asp/article.php/3581326

URL Rewriting with ASP.NET

http://www.codeproject.com/KB/aspnet/urlrewriter.aspx

ASP.NET: HttpModule for Query String Encryption - sundar k replied to praveen sinha on 08-Mar-08 09:45 PM

URL parameters or query strings are often used to carry information that can be used by hackers to do identity theft or other unpleasant things.

Consider the URL example.com/?user=123&account=456 and then imaging what a hacker could do with it. Security or not, sometimes you just don't want the visitors to see all the query strings for whatever reason.

In those cases it would be nice if we could encrypt the entire query string so it wouldn't carry any readable information. The problem with one big encrypted query string is that we would break all the code that referenced the query. Code like Request.QueryString["user"] would no longer work, but as usual ASP.NET has the answer to that problem.

What we need is an HttpModule that can turn the encrypted query string into a normal readable one, so that we can still use our old logic like Request.QueryString["user"]. In other words, we want the user to see this

?enc=VXzal017xHwKKPolDWQJoLACDqQ0fE//wGkgvRTdG/GgXIBDd1

while your code sees this

?user=123&account=456.

The HttpModule

The module we need for this task must be able to do a few simple things. It must be able to encrypt the regular query string so that all your current links will automatically be encrypted. It must also be able to decrypt it again so that you can write the code as you normally would. It must also provide a method for encrypting a regular query string if you don't want to use automatic encryption.

The most important feature of the module is to make it totally plug 'n play. You should be able to apply the module to any existing website and automatically have query string encryption and decryption without changing any of your code.

Implementation

Download the QueryStringModule.cs below and put it in the App_Code folder of your website. Then add the following lines to the web.config's section:

<httpModules>

   <add type="QueryStringModule" name="QueryStringModule"/>

</httpModules>

Because automatic encryption is not always desirable the module has a comment that tells you how to turn it off. The module is well commented and should be easy to modify for any ASP.NET developer.

Example

You can encrypt query strings by using the Encrypt() method of the module from any web page or user control.

string query = QueryStringModule.Encrypt("user=123&account=456");

Then just add the encrypted query string to the links that need encryption. You don't need to use the method if you use automatic encryption.

Download Source:

http://www.madskristensen.dk/blog/ct.ashx?id=a6a478df-245a-4cd8-a3cc-80bb8c9c8004&url=http%3a%2f%2fwww.madskristensen.dk%2fblog%2fcontent%2fbinary%2fQueryStringModule.zip

Original Article Link:

http://www.webpronews.com/expertarticles/2007/01/25/aspnet-httpmodule-for-query-string-encryption