Monday, 18 July 2011

How to Encrypt a Connection String with ASP.NET 4.0 C#


This tutorial will demonstrate how you can encrypt a connection string in the web.config file using ASP.NET 4.0 and C#.

Adding a Database
To demonstrate how to encrypt a connection string, we will need to create a simple web site with a database that we can connect to. At this point I have created a new ASP.NET Empty Web Site. To add the database:
  1. Right click the project in your solution explorer.
  2. Select add ASP.NET folder.
  3. Select App_Data.
  4. Right click the App_Data folder.
  5. Select add new item...
  6. Select a SQL Database.
  7. Name it 'Database.mdf'.
  8. Click add.
We migrated our web sites to Server Intellect over one weekend and the setup was so smooth that we were up and running right away. They assisted us with everything we needed to do for all of our applications. With Server Intellect's help, we were able to avoid any headaches!

Adding the ConnectionString
Now that our database is setup, we need to add a connection string to it in our Web.Config file. To do this, open up the Web.Config file for editing and add the following code between the <configuration> and <system.web> tags:
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
</connectionStrings>

I just signed up at Server Intellect and couldn't be more pleased with my fully scalable & redundant cloud hosting! Check it out and see for yourself.

Encrypting the ConnectionString
Next, we need to add a web form to the project to which we can add some C# code to encrypt the connection string that we have added. To do this:
  1. Right click the project in your solution explorer.
  2. Select add new item...
  3. Select a web form.
  4. Name it 'Default.aspx'.
  5. Open Default.aspx.cs up for editing.
  6. Add the following code to the Page_Load event method:
    protected void Page_Load(object sender, EventArgs e)
    {
        //open the config file
        Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
        //open the connection strings section
        ConfigurationSection section = config.GetSection("connectionStrings");

        //check to make sure it is not already encrypted
        if (!section.SectionInformation.IsProtected)
        {
            //encrypt it with RSA Protection
            section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
            //save the config file
            config.Save();
        }        
    }
Need help with cloud hosting? Try Server Intellect. We used them for our cloud hosting services and we are very happy with the results!

Testing
Next, all we need to do is load up the web site and ensure that our code to encrypt our connection string has executed. To do this, load up the web site. (Note: If you receive an error about opening the config file, ensure that you are running Microsoft Visual Studio as an administrator.) Once the web site is loaded and our code has executed, open up the Web.Config file again and notice that the connection string we added earlier has been encrypted. It should now look similar to this: 
<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>BnDTBlbZopzpE8iMxlzybg634r0T+96Q4D5/u5fOr+1hZ8t2sQNx4Gnk1RTZNlhdEVcPzzKSAK1oIJsTBYPeHRtIQ3MOqWcxprmZhvAE1CNcIy127mP3DKMPliH9UaSkM2qE63Xwe/dM1nuLHHvg+2fpPGH8uifD5LwNcfJYH6k=</CipherValue>
    </CipherData>
</EncryptedKey>
</KeyInfo>
<CipherData>
<CipherValue>H3WV1prcXup2P5gbJImBSwa8dQde2oU3PK0rAiCtr6sFBEJCUvJlLqyrzTuFJ56CsddrjTmJ42ayXryNfRD58GpTmW9OJAG80VVS5BM3bC8qIEvLNZIpVqiJcqjf5f16eXf8M98ERdY2I6F8Y018engXUO5oX8n2ryAd4SwS4Sj72KgwfcWGAZttbytWgEASgcJ5LGlyfHLi+gSGMyt+jV4z45D2uwZ0RQn/rWQjP77/RTtg1Ekyke49wL0abHjIjGOZl6czM1WqRxnck+X+7YCxvbcAEjCTTQojSiZWkc5RObphCCcMCFZC2qdZkczA0X8H6AesyXzSTLnqE4wPSNkd4kPOb/Vj</CipherValue>
</CipherData>
</EncryptedData>
</connectionStrings>

No comments:

Post a Comment