Introduction
Objective of this tutorial is to encrypt or decrypt web.config files in asp.net development project. Some of the web.config file contains sensitive information such as connection string to database, AppSettings values, etc. The function write in this tutorial is not auto execute, but require human action like click on button. This example will encrypt connectionStrings,appSettings and system.web/authentication section in web.config
Example:
- On asp.net project solution, create one dummy page to and insert 2 buttons in aspx page.
- Double click on the button to create an event for each button.
- Copy code behind below.
Example Code
Front End - ASPX page
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Encrypt" />
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Decrypt" />
</div>
</form>
</body>
Code Behind - .cs
using System;
using System.Configuration;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace EncDecryptWebconfig
{
public partial class EncDecrypt : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
//encrypt
string[] sectionName = { "connectionStrings", "appSettings", "system.web/authentication" };
string provider = "DataProtectionConfigurationProvider";
foreach (string a in sectionName)
{
Configuration config = WebConfigurationManager.OpenWebConfiguration("~/");
ConfigurationSection section = config.GetSection(a);
if (section != null &&
!section.SectionInformation.IsProtected)
{
section.SectionInformation.ProtectSection(provider);
config.Save();
}
}
}
protected void Button2_Click(object sender, EventArgs e)
{
//decrypt
string[] sectionName = { "connectionStrings", "appSettings", "system.web/authentication" };
foreach (string a in sectionName)
{
Configuration config = WebConfigurationManager.OpenWebConfiguration("~/");
ConfigurationSection section = config.GetSection(a);
if (section != null && section.SectionInformation.IsProtected)
{
section.SectionInformation.UnprotectSection();
config.Save();
}
}
}
}
}
Comments
Post a Comment