Friday, August 21, 2009

Encrypting sensitive information in web config

Scenario:
Web Config is another spot where usually people store important information in form of some AppSettings or Connection String information. Even though its no more a new topic, still most of the developer take it light. Its not that difficult to encrypt it any section of the Web.config

Solution:
Keep in mind, encrypting will not the change how you read the settings from C# code.

Code:

using System.Configuration;
using System.Web.Configuration;

Configuration config = WebConfigurationManager.OpenWebConfiguration(Context.Request.ApplicationPath);
ConfigurationSection sect = config.GetSection("appSettings");
if (!sect.SectionInformation.IsProtected) {
sect.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
config.Save();
}

Configuration config = WebConfigurationManager.OpenWebConfiguration("/");
ConfigurationSection sect = config.GetSection("appSettings");
if (sect.SectionInformation.IsProtected) {
sect.SectionInformation.UnprotectSection();
config.Save();
}
Web.Config:
<appSettings>
<add key="BlogAuthor" value="Sandeep" />
</appSettings>

<appSettings configProtectionProvider="RsaProtectedConfigurationProvider">
<EncryptedData>
<CipherData>
<CipherValue>AQAAANCM…dsadasdsaEWRSDFDS</CipherValue>
</CipherData>
</EncryptedData>
</appSettings>

0 comments: