devxlogo

Passing Information Securely Between ASP and ASP.NET

Passing Information Securely Between ASP and ASP.NET

ou can transfer information between systems using ASP.NET in multiple ways; however, many are cumbersome, complicated, or insecure. For example, many data transfer methods pass information in plain text, which makes the data vulnerable to both interception and misuse. This article centralizes the methods to interact with data used in both ASP and ASP.NET applications. You achieve this by using the same methods of encrypting and data-packaging in ASP.NET as in classic ASP?in other words, by calling .NET code via COM from classic ASP pages.

How ASP and ASP.NET Data-sharing Works
Here are two common ways to transfer data in an ASP/ASP.NET scenario. The first is a system in which servers transfer data based on a key provided by clients. This unique key identifier allows the two servers to contact each other directly and exchange the necessary information. You might see this in a passport-style authentication system. This article, however, uses a second method of transferring data. Instead of passing a unique token through the client, the data itself will be encrypted and transferred via the client to its destination server.

Inside the DataManager DLL
The central part of this application is the DataManager DLL, which manages the setting and encryption of key-value pairs. Select classes and functions contained in the DataManager are also registered for COM interop and are thus accessible from code in classic ASP pages as well.

Inside the DataManager.dll file, the Encryption class contains all the methods needed to encrypt data that will be transferred via the client. Behind the scenes the Encryption class uses a hash table to store key-value pairs added by calling the EncryptValue methods.

   public void EncryptValue(String strKey,       String strValue)   {      data.Add(strKey, strValue);         TextWriter tw = new StringWriter();      MemoryStream ms = new MemoryStream();         serializer.Serialize(ms, data);               encryptedData = Encrypt(        ASCIIEncoding.ASCII.GetString(ms.ToArray()),         "KEY");   }   

Author’s Note: This code was written in .NET 2.0; however, you should face no issues in converting it to 1.1, if needed.

Every time you call the EncyrptValue method to add a value, the code adds a new entry to the hash table. The EncryptValue method also computes the hash value using the Encrypt function. The Encrypt function called in the last line takes a string argument and returns an encrypted representation of that string. To improve your data security you could easily alter the code to use a more robust encryption technique involving security certificates.

See also  Custom Java Web Development - The Heartbeat of Modern Web Development

Also, note that the sample code stores only strings in the hash table; however you can use the same basic method to store a variety of objects. You could even use your own custom classes?but bear in mind that they must be both serializable and registered correctly for COM to work properly.

The Encryption class automatically Base64-encodes all data for transport by the browser when you call the appropriate methods. After the receiving server decodes the data, the class uses the serializer to reconstruct the hash table so it can access the values.

   public void SetEncrypted(string strEncrypted)   {      string decrypted;         encryptedData = strEncrypted;            // All inputs wil be Base64 encoded      strEncrypted =         System.Text.ASCIIEncoding.ASCII.GetString(        Convert.FromBase64String(strEncrypted));         // Decrypt data via specified encryption functions      decrypted = Decrypt(strEncrypted, "KEY");         data = (Hashtable)serializer.Deserialize(         new MemoryStream(         ASCIIEncoding.ASCII.GetBytes(decrypted)));   }

Registering DLL’s for Use by COM
This solution requires you to be able to access the .NET code in the DataManager dll from ASP. To do that, you must hook up the primary encryption class for COM so that the ASP page can create an instance of it. You won’t call the encryption methods directly from ASP code; instead, you’ll create an interface that contains all the methods needed by the ASP page, and call those via COM automation.

   ///    ///      Used for com interop interface   ///    [Guid("297AE33F-3EEF-4528-99EA-9C9866DC863C")]   [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]   public interface IDotNetInterface   {      String GetValue(string strKey);         void EncryptValue(String strKey, String strValue);         string GetEncrypted();         void SetEncrypted(string strEncrypted);   }      ///    ///      Used for encryption functions and algorithims   ///    [Guid("155BEB46-9B24-4eca-97DA-3B68BCAAE710")]   [ClassInterface(ClassInterfaceType.None)]   [ProgId("DataManager.Encryption")]   public class Encryption : IDotNetInterface   {   ...   }

The preceding code uses attributes to attach a GUID and a class interface to each object. Note that the code defines the interface type as COMInterfaceType.InterfaceIsIDispatch, which will allow the ASP page to access the interface functions via COM.

See also  Custom Java Web Development - The Heartbeat of Modern Web Development

After assembling the framework you need to register the DLL with the operating system, by adding the assembly to the GAC. To do this, open Windows Explorer and navigate to the Assembly folder in the Windows directory. After placing the assembly in the GAC you can use the regasm.exe tool to register the classes contained in the DLL. The regasm tool is installed with Microsoft Visual Studio; you can find it in the current version of the framework folder in your primary Windows install directory.

Encrypting and Decrypting Data
After building and registering the DataManager.dll for COM, you can create the pages that package and transfer the data. The example given in the downloadable code uses an ASP.NET (.aspx) page to transfer a keyed piece of data to a classic ASP (.asp) page and vice versa. The ASP page creates an instance of the Encryption class and uses that to decode the data and query the value that was passed in. The ASP page also provides a text box so you can submit data to be passed back to the .aspx page for decoding.

Here’s the code for the ASP page:

   dim serverSession      'Transfer to asp.net   if Request.Form("transfer") <> "" then      set serverSession = server.CreateObject(         "DataManager.Encryption")             call serverSession.EncryptValue("data",          request.Form("transfer"))             strEncrypted = serverSession.GetEncrypted             Response.Redirect("Default.aspx?i=" &          strEncrypted)   end if      'Transfer from asp.net   if Request.QueryString("i") <> "" then      ' Create the .NET object (it must be in the GAC       ' or this will fail).      ' Also object must be registered using regasm       ' found in the Framework folder      set serverSession = server.CreateObject(         "DataManager.Encryption")      call serverSession.SetEncrypted(         request.querystring("i"))   end if

In ASP.NET, the page code is:

   protected void Page_Load(object sender, EventArgs e)   {      if (!IsPostBack)      {         if (Request.QueryString["i"] == null)         {            lblTransfer.Visible = false;         }         else         {            Encryption enc = new Encryption();            enc.SetEncrypted(Request.QueryString["i"]);              lblTransfer.Text = "Passed in from ASP: " +               enc.GetValue("data");         }      }   }   protected void btnTransfer_Click(object sender, EventArgs e)   {      Encryption enc = new Encryption();      string redirectPath;         enc.EncryptValue("data", txtTransferValue.Text);         redirectPath =          "http://localhost/DataLink/ASPTest.asp?i=" +          enc.GetEncrypted();         if (redirectPath.Length < 2083)         Response.Redirect(redirectPath);      else         throw new Exception("URL has exceeded the " +            "maximum allowable URL length");   }   

The two methods shown above build a URL that passes the encrypted data using the variable i. Bear in mind that if the length of the data (plus the length of the URL itself) exceeds the maximum allowable length of a URL it will be truncated. The preceding code throws an exception if the URL being sent to the client exceeds 2083 characters, which is the maximum length of a GET request in Internet Explorer (other browsers may differ). In other words, this method works well for passing relatively small values. If the data you are encrypting is too long for a URL, you will instead need to use a combination of forms and JavaScript to pass the information from the source to the destination page as shown below.

                             

By passing the information using the form-based submission mechanism shown above, you aren't restricted to the maximum size of a URL string. You can easily modify the downloadable sample code for this article to retrieve values from the form collection rather than from the QueryString.

If you combine all the techniques discussed here, you can pass information easily between separate applications. The supplied sample code transfers data only between pages on the same site. However, by changing the destination URL you can pass data between separate sites and/or separate servers, using any combination of ASP.NET and ASP pages.

The data transfer method chosen for this example uses the client's browser to pass the information between sites, creating an easy and relatively secure method of transfer. While it does make the client process more information, it also means that you can pass information between two sites without having to set up a custom server-to-server communication mechanism.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist