Encrypting Connection Strings in ASP.Net 2.0

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

 

pic1.jpg

 

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>IFYvJC05w2MOn2YEF6wSM7jeBRKNPOh9Tm

CZGvOenjBDZh1/eiXlmA0+iX1txWLtoTllHNUQ
 f6dcC9RibnupGraROGAzE7Cm9PHdjrOcGuix

Ffo8fdhPhHvM6d9XPFGmcXrQdmpXJiDpdapeWIbdHeeH5FZNk
 m82quLmCCj8gWE=
</CipherValue>
 </
CipherData>
 </
EncryptedKey>
 </
KeyInfo>
 <
CipherData>
 <
CipherValue>UhQYqml3kH6RMtZsZHdrANn9SCC2+PiKzGi9w

C1e9A8Mg6PgnCS349sOayWyQKZJEswqxf
 A1E7U5NKsWcVVI3CFNjuc5lwpYrDOd2m7laNEczec4N6q0GCW1iqvG/

pVqMxzeRiKz5+CTO/ENSLDap4cCx
 8s0+RL85rFnOkHYiPgl1wSsfX4tnMhT0puvS7QAigK

Xwohhyo+KJsaCMS462dzTFY0mWpGStVwTatzPwSd
 u8gS+DK+yEnjeqx1ZlLWnYFjXaYjpGTgh/Reqnetov6+K82qhj

GL2jgjmJjJwhrkF0M8QCJwg1BsO26M7uXUF
 E6L/AsYBuRQXpG/gTFRXGnNrwVe1gIWx2kuyyGcmrU1qZ+3ZfYq

Yc5Bm85i6sPQGxVAR+gLTLtkV8Wm3iF
 RoujKTfwyzOEBzss6SXCHJ8N+C8Z2duYio3BnFsR5v+tqmzwlpq

+3r6024qhf8EJBs/5K0Q9OenA//jt0xawVK
 DT2cqUXw1ewZHrvLtdm1WoXFprbNSIFDDCgoXY2FTFYfiuU

FrwU3mxQ9NZOKPaa+cy4jnJynPJ6TD+Wu0
 bLd1vHH91oAzys7Jht7sUMoibG6E7Ou35IS6cRfdniWKc

Nu7iFcb6dWt+GwtJhnX1pvVxi6zhE0JE2SdL+X0R
 9zwxI2ww8GSGvCe/VAZYoaEnNeitTA31aan3b77RsT

+G9BIs5W+9xuTJ/Ho/AfcbARfLrNzLls6SdhOiaTJNW
 ir5sE4Sx1E6GQTrG9ygO4GVB9wZhGpeeCllt

QkIWRhqCIbXp3Rg==</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

 

 

 connstrings2.JPG

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. 


Similar Articles