Encrypt or decrypt sensitive data in Web.config

It is a very common practice to encrypt sensitive data in configuration files. This can be either database connection strings, public key, private key or credentials that need to be kept secure. As this secure data cannot be hard-coded into the application code, so it is stored in configuration files to facilitate modifying them at frequent intervals.

Configuration files used by ASP.NET applications are named as Web.config whereas Windows applications have App.config file. Though there are several symmetric and asymmetric algorithms available in the market, the .Net framework provides an out-of-the-box feature to encrypt and decrypt configuration file or its section.

Let's consider an appSettings section of App.config that needs to be encrypted:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <startup> 
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
  </startup>
  <appSettings>
    <add key="DbPassword" value="Test12345" />
  </appSettings>
</configuration>

Below code snippet does the encrypt to Cipher text using DataProtectionConfigurationProvider:
private void btnEncrypt_Click(object sender, RoutedEventArgs e)
{
  Configuration config = ConfigurationManager.OpenExeConfiguration(
                System.Reflection.Assembly.GetExecutingAssembly().Location);
  ConfigurationSection section = config.GetSection("appSettings");
  if (!section.SectionInformation.IsProtected)
  {
    section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
    config.Save();
  }
  MessageBox.Show(ConfigurationManager.AppSettings["DbPassword"]);
}

Once encrypted, the content of appSettings will not be readable to the user. However .Net code will still be able to read it in its original form. Below is an example of the encrypted appSetting section:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
    </startup>
    <appSettings configProtectionProvider="DataProtectionConfigurationProvider">
        <EncryptedData>
            <CipherData>
                <CipherValue>AXAAANMCdndereAwedwDC/C1................................</CipherValue>
            </CipherData>
        </EncryptedData>
    </appSettings>
</configuration>

As and when required the encrypted section can be easily decrypted into its original form. This can be achieved by the below piece of code:
private void btnDecrypt_Click(object sender, RoutedEventArgs e)
{
  Configuration config = ConfigurationManager.OpenExeConfiguration(
                System.Reflection.Assembly.GetExecutingAssembly().Location);
  ConfigurationSection section = config.GetSection("appSettings");
  if (section.SectionInformation.IsProtected)
  {
    section.SectionInformation.UnprotectSection();
    config.Save();
  }
  MessageBox.Show(ConfigurationManager.AppSettings["DbPassword"]);
}

No comments:

Post a Comment