Encrypting/Decrypting
web.config sections in ASP.Net
using
System.Configuration;
using
System.Web.Configuration;
public
partial
class
_Default
: System.Web.UI.Page
{
protected
void
Encripting_Click(object
sender, EventArgs
e)
{
EncriptSection("appSettings",
"DataProtectionConfigurationProvider");
}
protected
void
Decripting_Click(object
sender, EventArgs
e)
{
DecriptSection("appSettings");
}
//
section name may be connectionStrings, appSettings
private
void
EncriptSection(string
sectionName, string
provider)
{
Configuration
config
=WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection
section =config.GetSection(sectionName);
if
(section != null
&& !section.SectionInformation.IsProtected)
{
section.SectionInformation.ProtectSection(provider);
config.Save();
}
}
private
void
DecriptSection(string
sectionName)
{
Configuration
config
=WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection
section =config.GetSection(sectionName);
if
(section != null
&& section.SectionInformation.IsProtected)
{
section.SectionInformation.UnprotectSection();
config.Save();
}
}
}
Code in Web.config
Before Encripting :
<appSettings>
<add
key="SiteName"
value="My
Website"
/>
<add
key="SecretKey"
value="12345678"
/>
</appSettings>
After
Encripting :
<appSettings
configProtectionProvider="DataProtectionConfigurationProvider">
<EncryptedData>
<CipherData>
<CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAiH5JpzUAjkeIVeSHggMo3gQAAAACAAAAAAAD
</CipherValue>
</CipherData>
</EncryptedData>
</appSettings>
You
can access Key values asusually by writing
string
sValue = ConfigurationSettings.AppSettings["SiteName"];
The ASP.NET Wiki was started by Scott Hanselman in February of 2008. The idea is that folks spend a lot of time trolling the blogs, googlinglive-searching for answers to common "How To" questions. There's piles of fantastic community-created and MSFT-created content out there, but if it's not found by a search engine and the right combination of keywords, it's often lost.
The ASP.NET Wiki articles moved to CodeProject in October 2013 and will live on, loved, protected and updated by the community.