Decrypting a configuration file can be done with the help of
the method shown below, Decrypt. The Decrypt method simply checks if the
configuration section is encrypted. If it is encrypted then it decrypts the
same. The same is shown in listing 8. The code below assumes that the reader is
well versed with programming in C#. Some of the classes are new in .NET Framework
2.0
Listing 8
private void Decrypt()
{
// Open the Configuration file
Configuration ObjConfiguration =
WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
// Open a section in the configuration file
AppSettingsSection ObjAppSettingsSection = ObjConfiguration.AppSettings;
// Checking if the section information is protected
if (ObjAppSettingsSection.SectionInformation.IsProtected)
{
// Decrypt the section
ObjAppSettingsSection.SectionInformation.UnprotectSection();
//Save the changes after decryption
ObjConfiguration.Save();
}
// Reading the values after De-crypting configuration file
Response.Write(ConfigurationManager.AppSettings["Key"].ToString());
}
Decrypting the configuration file involves loading the
configuration file in the Configuration object. Reading the section for which
the encryption is done, check that the section is protected. If it is protected
then unprotect the section. The changes done to the configuration need to be
persisted back to the configuration file. Therefore, save the changes.
Listing 9
// Checking if the section information is protected
if (ObjAppSettingsSection.SectionInformation.IsProtected)
{
// Decrypt the section
ObjAppSettingsSection.SectionInformation.UnprotectSection();
//Save the changes after decryption
ObjConfiguration.Save();
}
Listing 9 has the code in C# where the section information
is checked for protection. This is done by the IsProtected method of
SectionInformation class. If it returns true then the SectionInformation’s
method UnprotectSection is called. This method simply decrypts the
configuration and changes the configuration to its previous state. Once the changes
are done then the Configuration is saved back to the configuration.