Encrypting and 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="WebName" value="Ujjwala Datta Kalluri Blog" />

<add key="KeyValue" value="2727" />

</appSettings>


After Encripting :


<appSettings configProtectionProvider="DataProtectionConfigurationProvider">

<EncryptedData>

<CipherData>

<CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAiH5JpzUAjkeIVeSHggMo3gQAA=</CipherValue>

</CipherData>

</EncryptedData>

</appSettings>

You can access Key values asusually by writing

 

string sValue = ConfigurationSettings.AppSettings["WebName"];

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s