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"];

Comments

Popular posts from this blog

How to create RSS Feed in Asp.Net

Auto generate change scripts in SQL Server Management Studio SSMS for tables

HOW TO Use the NumericUpDown Control