Encrypting and decrypting the connection string.


In this article we will discuss how can we access the configuration files section in the code behind in pages and then can encrpyt or decrypt the particular sections. Here we will encrypt and decypt the connection string from code behind.

Now in the design page we will take three buttons one each for getting all connection string
from config file, encrypting the connection string and decrypting the connection string.
Now on the button clicks we will access the configuration file
using WebConfigurationManager and then perform the changes.

Note:

WebConfigurationManager will access the configuration file.
OpenWebConfiguration will open the configuration file.
GetSection will allow us to access the specific section.
SectionInformation.IsProtected will give the information about the particular section that
it is protected or not.


protected void btn_encrypt_Click(object sender, EventArgs e)
{
Configuration c = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection cs = c.Sections["appSettings"];

if (!cs.SectionInformation.IsProtected)
{
cs.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
c.Save();
Label1.Text = "Encrypted";
}
else
{
Label1.Text = "Section is already encrypted";
}
}
protected void btn_showconnectionstrings_Click(object sender, EventArgs e)
{
foreach (ConnectionStringSettings css in ConfigurationManager.ConnectionStrings)
{
Label1.Text = "Name: " + css.Name;
Label1.Text += "
Connection String: " + css.ConnectionString;
}
}
protected void btn_decrypt_Click(object sender, EventArgs e)
{
Configuration c = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection cs = c.Sections["connectionStrings"];

if (cs.SectionInformation.IsProtected)
{
cs.SectionInformation.UnprotectSection();
c.Save();
Label1.Text = "Decrypted";
}
else
{
Label1.Text = "Section is already decrypted";
}
}


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: