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.

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.

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.

devx-admin

devx-admin

Share the Post:
Military Drones Revolution

Military Drones: New Mobile Command Centers

The Air Force Special Operations Command (AFSOC) is currently working on a pioneering project that aims to transform MQ-9 Reaper drones into mobile command centers

Huge Savings

Score Massive Savings on Portable Gaming

This week in tech bargains, a well-known firm has considerably reduced the price of its portable gaming device, cutting costs by as much as 20

Cloudfare Protection

Unbreakable: Cloudflare One Data Protection Suite

Recently, Cloudflare introduced its One Data Protection Suite, an extensive collection of sophisticated security tools designed to protect data in various environments, including web, private,

Drone Revolution

Cool Drone Tech Unveiled at London Event

At the DSEI defense event in London, Israeli defense firms exhibited cutting-edge drone technology featuring vertical-takeoff-and-landing (VTOL) abilities while launching two innovative systems that have

2D Semiconductor Revolution

Disrupting Electronics with 2D Semiconductors

The rapid development in electronic devices has created an increasing demand for advanced semiconductors. While silicon has traditionally been the go-to material for such applications,

Cisco Growth

Cisco Cuts Jobs To Optimize Growth

Tech giant Cisco Systems Inc. recently unveiled plans to reduce its workforce in two Californian cities, with the goal of optimizing the company’s cost structure.

Military Drones Revolution

Military Drones: New Mobile Command Centers

The Air Force Special Operations Command (AFSOC) is currently working on a pioneering project that aims to transform MQ-9 Reaper drones into mobile command centers to better manage smaller unmanned

Huge Savings

Score Massive Savings on Portable Gaming

This week in tech bargains, a well-known firm has considerably reduced the price of its portable gaming device, cutting costs by as much as 20 percent, which matches the lowest

Cloudfare Protection

Unbreakable: Cloudflare One Data Protection Suite

Recently, Cloudflare introduced its One Data Protection Suite, an extensive collection of sophisticated security tools designed to protect data in various environments, including web, private, and SaaS applications. The suite

Drone Revolution

Cool Drone Tech Unveiled at London Event

At the DSEI defense event in London, Israeli defense firms exhibited cutting-edge drone technology featuring vertical-takeoff-and-landing (VTOL) abilities while launching two innovative systems that have already been acquired by clients.

2D Semiconductor Revolution

Disrupting Electronics with 2D Semiconductors

The rapid development in electronic devices has created an increasing demand for advanced semiconductors. While silicon has traditionally been the go-to material for such applications, it suffers from certain limitations.

Cisco Growth

Cisco Cuts Jobs To Optimize Growth

Tech giant Cisco Systems Inc. recently unveiled plans to reduce its workforce in two Californian cities, with the goal of optimizing the company’s cost structure. The company has decided to

FAA Authorization

FAA Approves Drone Deliveries

In a significant development for the US drone industry, drone delivery company Zipline has gained Federal Aviation Administration (FAA) authorization, permitting them to operate drones beyond the visual line of

Mortgage Rate Challenges

Prop-Tech Firms Face Mortgage Rate Challenges

The surge in mortgage rates and a subsequent decrease in home buying have presented challenges for prop-tech firms like Divvy Homes, a rent-to-own start-up company. With a previous valuation of

Lighthouse Updates

Microsoft 365 Lighthouse: Powerful Updates

Microsoft has introduced a new update to Microsoft 365 Lighthouse, which includes support for alerts and notifications. This update is designed to give Managed Service Providers (MSPs) increased control and

Website Lock

Mysterious Website Blockage Sparks Concern

Recently, visitors of a well-known resource website encountered a message blocking their access, resulting in disappointment and frustration among its users. While the reason for this limitation remains uncertain, specialists

AI Tool

Unleashing AI Power with Microsoft 365 Copilot

Microsoft has recently unveiled the initial list of Australian clients who will benefit from Microsoft 365 (M365) Copilot through the exclusive invitation-only global Early Access Program. Prominent organizations participating in

Microsoft Egnyte Collaboration

Microsoft and Egnyte Collaboration

Microsoft has revealed a collaboration with Egnyte, a prominent platform for content cooperation and governance, with the goal of improving real-time collaboration features within Microsoft 365 and Microsoft Teams. This

Best Laptops

Top Programming Laptops of 2023

In 2023, many developers prioritize finding the best laptop for programming, whether at home, in the workplace, or on the go. A high-performing, portable, and user-friendly laptop could significantly influence

Renaissance Gaming Magic

AI Unleashes A Gaming Renaissance

In recent times, artificial intelligence has achieved remarkable progress, with resources like ChatGPT becoming more sophisticated and readily available. Pietro Schirano, the design lead at Brex, has explored the capabilities

New Apple Watch

The New Apple Watch Ultra 2 is Awesome

Apple is making waves in the smartwatch market with the introduction of the highly anticipated Apple Watch Ultra 2. This revolutionary device promises exceptional performance, robust design, and a myriad

Truth Unveiling

Unveiling Truths in Bowen’s SMR Controversy

Tony Wood from the Grattan Institute has voiced his concerns over Climate and Energy Minister Chris Bowen’s critique of the Coalition’s support for small modular nuclear reactors (SMRs). Wood points

Avoiding Crisis

Racing to Defy Looming Financial Crisis

Chinese property developer Country Garden is facing a liquidity challenge as it approaches a deadline to pay $15 million in interest associated with an offshore bond. With a 30-day grace

Open-Source Development

Open-Source Software Development is King

The increasingly digital world has led to the emergence of open-source software as a critical factor in modern software development, with more than 70% of the infrastructure, products, and services

Home Savings

Sensational Savings on Smart Home Security

For a limited time only, Amazon is offering massive discounts on a variety of intelligent home devices, including products from its Ring security range. Running until October 2 or while

Apple Unleashed

A Deep Dive into the iPhone 15 Pro Max

Apple recently unveiled its groundbreaking iPhone 15 Pro and iPhone 15 Pro Max models, featuring a revolutionary design, extraordinary display technology, and unrivaled performance. These new models are the first

Renewable Crypto Miners

Crypto Miners Embrace Renewable Energy?

As the cryptocurrency sector deals with the fallout from the FTX and Celsius exchange collapses, Bitcoin miners are increasingly exploring alternative energy sources to reduce expenses and maintain profitability. Specialists

Laptop Savings

The HP Omen 16 is a Gamer’s Dream

Best Buy is currently offering an unbeatable deal on the HP Omen 16 gaming laptop, giving potential buyers the chance to save a significant $720 on their purchase. Originally priced

How to Check for Vulnerabilities in Exchange Server

It is imperative to keep your systems and infrastructure up-to-date to mitigate security issues and loopholes, and to protect them against any known vulnerabilities and security risks. There are many

Data Center Creation

Transforming Corporate Campuses into Thriving Data Centers

Dallas-based developer Compass Datacenters has purchased a 197-acre ex-corporate campus in Hoffman Estates, Illinois for an estimated $194 million. This acquisition occurs as more companies are downsizing and consolidating their

Nano Unbeatable Value

Lenovo ThinkPad X1 Nano: Unbeatable Value

The Lenovo ThinkPad X1 Nano, a first-generation model beloved for its ergonomic keyboards and stylish appearance, is now available at an unbeatable price of $600 on eBay. Though this 13-inch