You can easily encrypt sections of web.config in ASP.NET 2.0. In the code below I have encrypted the ConnectionStrings section of web.config.
Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection configSection = config.GetSection("connectionStrings");
if (configSection.SectionInformation.IsProtected)
{
configSection.SectionInformation.UnprotectSection();
config.Save();
}
else
{
configSection.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
config.Save();
}
.NET Framework 2.0 introduces a protected configuration feature that you can use to encrypt sensitive configuration file data by using a command line tool. The following two protected configuration providers are provided although you can also implement custom providers.
- RSAProtectedConfigurationProvider : This is the default provider and uses the RSA public key encryption to encrypt and decrypt data.
- DPAPIProtectedConfigurationProvider : This provider uses the Windows Data Protection API (DPAPI) to encrypt and decrypt data.
You can also writing connection string dynamically:
Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConnectionStringsSection conSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
conSection.ConnectionStrings["SQLConnectionString"].ConnectionString = "NewConnectionString";
config.Save();
[Please note that when you write to a web.config file the application restarts which means all the session and application variables are lost.]
No comments:
Post a Comment