Encrypting and decrypting sensitive data in your web.config files using Protected configuration - Part IV
Hi All, It this closing post on the subject of Encrypting web.config data, I would like to show how to encrypt the sensitive data at runtime. Why? you ask, because for example we wish to deploy our code and see what the web.config contains before it is encrypted. or we would like to change the connection string or any appSettings data in a readable way.
So, here is a simple code that does exactly that:
protected void Page_Load(object sender, EventArgs e)
{
EncryptConfig();
}
private void EncryptConfig()
{
// Open the Web.config file.
Configuration config =
WebConfigurationManager.OpenWebConfiguration("~");
// Get the connectionStrings section.
ConnectionStringsSection section =
config.GetSection("connectionStrings")
as ConnectionStringsSection;
// Toggle encryption.
if (section.SectionInformation.IsProtected)
{
section.SectionInformation.UnprotectSection();
}
else
{
if (!section.SectionInformation.IsLocked)
{
section.SectionInformation.
ProtectSection("RsaProtectedConfigurationProviderqqq"); section.SectionInformation.ForceSave = true;
//Save changes to the Web.config file.
config.Save(ConfigurationSaveMode.Full);
}
}
}
Couple of things to notice here:
1. This code is better of being in a some base page so that when the user enters some page in your app, you guaranty that the base page code is called.
2. You can write the same code for Encrypting the app setting section as well.
3. Notice the name of the container key i am using, "RsaProtectedConfigurationProviderqqq".
This is the name of the RSA provider i added to my machine.config file after creating a container key.