Thursday, August 14, 2008

Encrypting ConnectionString in web.config

To work-out this sample you need to include System.Web.Configuration namespace.

Code:

using System.Web.Configuration;

// Open web.config file
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");

// Get the ConnectionString section
ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection;

// Toggle Encryption
if (section.SectionInformation.IsProtected)
{
section.SectionInformation.UnprotectSection();
Response.Write("Connection String Encryption Removed");
}
else
{
section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
Response.Write("Connection String Encrypted");
}

// Save changes to web.config file
config.Save();

Note:
Include this code in a Page-Load or in a Button-Click. The code sample toggles encryption-decryption. This is a code sample from MSDN.

No comments:

 
Best viewed in Internet Explorer 8.