Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » How do I » Encrypting Connection Strings in ASP.Net 2.0

Encrypting Connection Strings in ASP.Net 2.0

This article describes how to encrypt the connection strings section in ASP.Net 2.0 web.config files and demonstrates the transperancy of using encrypted connection strings in your web application.

Author Rank:
Technologies: ASP.NET 1.0,Visual C# .NET
Total downloads :
Total page views :  19321
Rating :
 0/5
This article has been rated :  0 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
Become a Sponsor


Related EbooksTop Videos

ASP.NET 2.0 allows storing connectionString elements within the connectionStrings section in web.config. The web.config section containing connection strings can be encrypted for security. The connectionStrings section is commonly used in most applications as the intuitive location for storing the web application's connection strings and the encrypting of this section will provide a layer of security over frequently used sensitive information.

 

In the following sample, we will build a web page which allows the user of the web page to encrypt and decrypt the connectionStrings section of the web.config file. It will also provide a view of the connection string contents within the web.config file and allow the user to add a new connection string. This sample will demonstrate that no additional action is required to work with the connection strings in ASP.Net, irrespective of whether the contents have been encrypted. The extra layer of security applied to the sensitive information will not add any overhead for the developer.

 

Similarly, you can bind to a database, by accessing the connection string from the web.config, irrespective of whether the connectionStrings section has been encrypted. Again, this indicates the transparency available in implementing connection string encryption in ASP.Net 2.0.

 

The utility of this sample is that you can re-use this code across web applications by simply copying the webpage to the web application.

 

Image: View of the utility web page

 

 

Sample 1: Encrypt the connectionStrings Section

 

protected void btnEncrypt_Click(object sender, EventArgs e)

{

//Specify the location for the web.config file that needs to be encrypted

 

Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);

ConfigurationSection section = config.GetSection("connectionStrings");

//Check if the section is already encrypted

if (section != null && !section.SectionInformation.IsProtected)

{

try

{

//Encrypt the web.config section.

section.SectionInformation.ProtectSection("RSAProtectedConfigurationProvider");

config.Save();

lblStatus.Text = "The Connection String Section has been encrypted successfully.";

}

catch

{

lblStatus.Text = "Error occured while encrypting the Connection Strings section";

}

}

else

lblStatus.Text = "Either the Connection Strings Section does not exist or is already encrypted";

}

 

Note that ASP.Net 2.0 Configuration Manager provides 2 in-built options, DPAPI and RSA, for the encryption algorithm to be used.

 

After you run the above code and the web.config has been encrypted, you can open up the web.config file in your ASP.Net project. The contents of the web.config section will now appear encrypted.

 

<connectionStrings configProtectionProvider="RsaProtectedConfigurationProvider">

<EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element"

xmlns="http://www.w3.org/2001/04/xmlenc#">

<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />

<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">

<EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#">

<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />

<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">

<KeyName>Rsa Key</KeyName>

</KeyInfo>

<CipherData>

<CipherValue>IFYvJC05w2MOn2YEF6wSM7jeBRKNPOh9TmCZGvOenjBDZh1/eiXlmA0+iX1txWLtoTllHNUQ
f6dcC9RibnupGraROGAzE7Cm9PHdjrOcGuixFfo8fdhPhHvM6d9XPFGmcXrQdmpXJiDpdapeWIbdHeeH5FZNk
m82quLmCCj8gWE=
</CipherValue>

</CipherData>

</EncryptedKey>

</KeyInfo>

<CipherData>

<CipherValue>UhQYqml3kH6RMtZsZHdrANn9SCC2+PiKzGi9wC1e9A8Mg6PgnCS349sOayWyQKZJEswqxf
A1E7U5NKsWcVVI3CFNjuc5lwpYrDOd2m7laNEczec4N6q0GCW1iqvG/pVqMxzeRiKz5+CTO/ENSLDap4cCx
8s0+RL85rFnOkHYiPgl1wSsfX4tnMhT0puvS7QAigKXwohhyo+KJsaCMS462dzTFY0mWpGStVwTatzPwSd
u8gS+DK+yEnjeqx1ZlLWnYFjXaYjpGTgh/Reqnetov6+K82qhjGL2jgjmJjJwhrkF0M8QCJwg1BsO26M7uXUF
E6L/AsYBuRQXpG/gTFRXGnNrwVe1gIWx2kuyyGcmrU1qZ+3ZfYqYc5Bm85i6sPQGxVAR+gLTLtkV8Wm3iF
RoujKTfwyzOEBzss6SXCHJ8N+C8Z2duYio3BnFsR5v+tqmzwlpq+3r6024qhf8EJBs/5K0Q9OenA//jt0xawVK
DT2cqUXw1ewZHrvLtdm1WoXFprbNSIFDDCgoXY2FTFYfiuUFrwU3mxQ9NZOKPaa+cy4jnJynPJ6TD+Wu0
bLd1vHH91oAzys7Jht7sUMoibG6E7Ou35IS6cRfdniWKcNu7iFcb6dWt+GwtJhnX1pvVxi6zhE0JE2SdL+X0R
9zwxI2ww8GSGvCe/VAZYoaEnNeitTA31aan3b77RsT+G9BIs5W+9xuTJ/Ho/AfcbARfLrNzLls6SdhOiaTJNW
ir5sE4Sx1E6GQTrG9ygO4GVB9wZhGpeeClltQkIWRhqCIbXp3Rg==
</CipherValue>

</CipherData>

</EncryptedData>

</connectionStrings>

 

Sample 2: Decrypt the connectionStrings Section

 

The following code snippet illustrates the procedure to decrypt the connectionStrings section that has been encrypted as above. 

 

protected void btnDecrypt_Click(object sender, EventArgs e)

{

Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);

ConfigurationSection section = config.GetSection("connectionStrings");

if (section != null && section.SectionInformation.IsProtected)

{

try

{

section.SectionInformation.UnprotectSection();

config.Save();

lblStatus.Text = "The Connection String Section has been decrypted successfully.";

}

catch

{

lblStatus.Text = "Error occured while decrypting the Connection Strings section";

}

}

else

lblStatus.Text = "Either the Connection Strings Section does not exist or is not encrypted";

} 

 

Sample 3: Check if the connectionStrings section has been encrypted

 

Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);

ConfigurationSection section = config.GetSection("connectionStrings");

bIsProtected = section.SectionInformation.IsProtected;

lblStatus.Text = "The Connection Strings Section has ";

if (!bIsProtected)

lblStatus.Text += "not ";

lblStatus.Text += "been encrypted.";

 

Sample 4: Add a new connectionString to the web.config (Same code regardless of whether the section has been encrypted)

 

Try

{

Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);

config.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings(txtConnStringKey.Text, txtConnStringValue.Text));

config.Save();

lblStatus.Text = "The Connection String has been added successfully";

}

catch

{

lblStatus.Text = "Error occured while adding the connection string.";

}

 

Sample 5: View the connectionStrings web.config Section (Same code, regardless of whether the section has been encrypted).

 

In the following code snippet, the contents of the ConnectionStrings Section are displayed in a GridView control.

 

private void DisplayConnStrings()

{

Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);

grdConnStrings.DataSource = config.ConnectionStrings.ConnectionStrings;

grdConnStrings.DataBind();

} 

 

Referencing the Configuration File in Code

 

The OpenWebConfiguration method of the WebConfigurationManager object is used to get a reference to the web.config file. This method has 6 overloads and you can chose the appropriate overload method for your requirements. These classes are available in the System.Web.Configuration namespace.

 

Important Note: Do make sure this appropriate security is setup for this web page. If not, it will defeat the very purpose that the article was setup to demonstrate.

 

Image: Connection String Utility Form Design

 

 

 

Code Listing: Connection String Utility - Util_ConnStringEncrypt.aspx

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Util_ConnStringEncrypt.aspx.cs" Inherits="Util_ConnStringEncrypt" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>Web.Config Connection Strings Encryption Utility</title>

</head>

<body>

    <form id="form1" runat="server">

    

        <H3>ASP.Net Utility - Connection String Encryption</H3><hr />

        <asp:Label ID="lblStatus" runat="server" Text=""></asp:Label><br />

        <asp:Button ID="btnEncrypt" runat="server" Text="Encrypt" OnClick="btnEncrypt_Click" /><br />

        <asp:Button ID="btnDecrypt" runat="server" Text="Decrypt" OnClick="btnDecrypt_Click" /><br />

        <hr />

        Connection Strings:&nbsp;<asp:GridView ID="grdConnStrings" runat="server" BackColor="White"

            BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black"

            GridLines="Vertical">

            <FooterStyle BackColor="#CCCC99" />

            <RowStyle BackColor="#F7F7DE" />

            <SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />

            <PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />

            <HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />

            <AlternatingRowStyle BackColor="White" />

        </asp:GridView>

        <br />

        <hr />

        <table>

            <tr>

                <td style="width: 100px">

        Connection String Key:</td>

                <td style="width: 149px">

        <asp:TextBox ID="txtConnStringKey" runat="server"></asp:TextBox></td>

                <td style="width: 21px">

                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtConnStringKey"

                        ErrorMessage="RequiredFieldValidator" ValidationGroup="vgrpAdd">*</asp:RequiredFieldValidator></td>

            </tr>

            <tr>

                <td style="width: 100px">

        Connection String Value:</td>

                <td style="width: 149px">

        <asp:TextBox ID="txtConnStringValue" runat="server" Width="387px"></asp:TextBox></td>

                <td style="width: 21px">

                    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtConnStringValue" ErrorMessage="RequiredFieldValidator" ValidationGroup="vgrpAdd">*</asp:RequiredFieldValidator></td>

            </tr>

            <tr>

                <td style="width: 100px">

                    Provider:</td>

                <td style="width: 149px">

                    <asp:TextBox ID="txtProvider" runat="server"

                        Width="398px"></asp:TextBox></td>

                <td style="width: 21px">

                    <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtProvider"

                        ErrorMessage="Please enter the Value for the connection string." ValidationGroup="vgrpAdd">*</asp:RequiredFieldValidator></td>

            </tr>

        </table>

        &nbsp;&nbsp;<br />

        <asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="btnAdd_Click" /><br />

        &nbsp;&nbsp;<br />

        <asp:ValidationSummary ID="ValidationSummary1" runat="server" HeaderText="The following data is required for adding a new Connection String" ValidationGroup="vgrpAdd" />

        <br />

        &nbsp;<br />

    </form>

</body>

</html>

 

Code Listing: Connection String Utility - Util_ConnStringEncrypt.aspx.cs (Please watch out for line wrapping in the code)

 

using System;

using System.Data;

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.Web.Configuration;

 

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

{

    protected void Page_Load(object sender, EventArgs e)

    {

        bool bIsProtected=false;

        if (!IsPostBack)

        {

            try

            {

                Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);

                ConfigurationSection section = config.GetSection("connectionStrings");

                bIsProtected = section.SectionInformation.IsProtected;

                lblStatus.Text = "The Connection Strings Section has ";

                if (!bIsProtected)

                    lblStatus.Text += "not ";

                lblStatus.Text += "been encrypted.";

 

                DisplayConnStrings();

            }

            catch

            {

                lblStatus.Text = "Cannot determine the encryption status of the Connection String Section";

            }

        }

    }

 

    protected void btnEncrypt_Click(object sender, EventArgs e)

    {

        Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);

        ConfigurationSection section = config.GetSection("connectionStrings");

        if (section != null && !section.SectionInformation.IsProtected)

        {

            try

            {

                section.SectionInformation.ProtectSection("RSAProtectedConfigurationProvider");

                config.Save();

                lblStatus.Text = "The Connection String Section has been encrypted successfully.";

            }

            catch

            {

                lblStatus.Text = "Error occured while encrypting the Connection Strings section";

            }

        }

        else

            lblStatus.Text = "Either the Connection Strings Section does not exist or is already encrypted";

    }

    protected void btnDecrypt_Click(object sender, EventArgs e)

    {

        Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);

        ConfigurationSection section = config.GetSection("connectionStrings");

        if (section != null && section.SectionInformation.IsProtected)

        {

            try

            {

                section.SectionInformation.UnprotectSection();

                config.Save();

                lblStatus.Text = "The Connection String Section has been decrypted successfully.";

            }

            catch

            {

                lblStatus.Text = "Error occured while decrypting the Connection Strings section";

            }

        }

        else

            lblStatus.Text = "Either the Connection Strings Section does not exist or is not encrypted";

    }

 

    protected void btnAdd_Click(object sender, EventArgs e)

    {

        try

        {

            Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);

            config.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings(txtConnStringKey.Text, txtConnStringValue.Text,txtProvider.Text));

            config.Save();

            lblStatus.Text = "The Connection String has been added successfully";

            DisplayConnStrings();

        }

        catch

        {

          lblStatus.Text = "Error occured while adding the connection string.";

        }

    }

 

    private void DisplayConnStrings()

    {

        Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);

        grdConnStrings.DataSource = config.ConnectionStrings.ConnectionStrings;

        grdConnStrings.DataBind();

    }

}

 

Conclusion

 

In this article we saw how to encrypt the connection strings section in ASP.Net 2.0 web.config files and the transparency in using encrypted connection strings in your web application.

 

Disclaimer

This article is for purely educational purposes and is a compilation of notes, material and my understanding on this subject. Any resemblance to other material is an un-intentional coincidence and should not be misconstrued as malicious, slanderous, or any anything else hereof. 


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Dipal Choksi
Dipal Choksi has over 10 years of industry experience in team-effort projects and also as an individual contributor. She has been working on the .Net platform since the beta releases of .Net 1.0.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Microsoft Visual Studio 2010 offers more to developers than any other Visual Studio release. Work more productively and collaboratively-with greater control over your work at every step. The Beta 2 can give you a head start on achieving efficiency.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
connction string by ramya On May 4, 2007
i hav a doubt in connction string....in my project i hav used the connection string in web.config file and opened the connection in every form using ,con.open.my doubt is there any way to open the connection once instead of opening it on every form load....plz clear my doubt...
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved