The .NET Framework provides configuration files - app.config and web.config - to store application-wide configurable information.

But these are just text files, so they can be read by anyone with the proper permissions. What if I want to store sensitive information in this file, such as a password or a connection string?f

Fortunately, the .NET Framework also provides a mechanism for encrypting parts of a config file. This functionality is available in the System.Configuration namespace in the System.Configuration assembly, so you will need to set a reference to this assembly (Project | Add Reference | .NET tab) and add the following line to the top of your class file
using System.Configuration;

The ConfigurationManager.OpenExeConfiguration static method accepts the name of an assembly and returns a Configuration object that can be used to manipulate the config file. It is important to remember that, when a project is built, the project's app.config file is renamed to {AssemblyName}.exe.config and copied to the bin\Debug or bin\Release folder (depending on the build configuration). It is the {AssemblyName}.exe that is passed into the OpenExeConfiguration method and it is the config file under the bin folder that will be affected by our code.

For example, the following code creates a Configuration object to read and manipulate the config file associated with the MyAwesomeApp.exe assembly

string appName = "MyAwesomeApp.exe";
Configuration config = ConfigurationManager.OpenExeConfiguration(appName);

We can call the Configuration object's GetSection method to get a reference to a particular section of the config file. For example, if we want to work with the connectionStrings section, we use the code

var section = (ConnectionStringsSection) config.GetSection("connectionStrings");

Now we can check to see if the section is already encrypted (IsProtected property), encrypt the section (ProtectSection method), or decrypt the section (UnprotectSection method). The following code encrypts the connectionString section

string appName = "MyAwesomeApp.exe";
Configuration config = ConfigurationManager.OpenExeConfiguration(appName);
ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection;
if (!section.SectionInformation.IsProtected)
{
    section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
}
config.Save();


The code below decrypts the connectionString section

string appName = "MyAwesomeApp.exe";
Configuration config = ConfigurationManager.OpenExeConfiguration(appName);
ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection;
if (section.SectionInformation.IsProtected)
{
    //it is so we need to remove the encryption
    section.SectionInformation.UnprotectSection();
}
config.Save();

The final step is to write changes back to the file by calling the Configuration object's Save method.
config.Save();

Below is the unencrypted config file

"1.0" encoding="utf-8" ?>

  
    "MyApp_Dev" connectionString="Data Source=Server01;Initial Catalog=AwesomeDB_Dev;Integrated Security=True"/>
    "MyApp_QA" connectionString="Data Source=Server01;Initial Catalog=AwesomeDB_QA;Integrated Security=True"/>
    "MyApp_Prod" connectionString="Data Source=Server01;Initial Catalog=AwesomeDB;Integrated Security=True"/>
  
  
    "CompanyName" value="The Awesome Company"/>
    "CompanyPhone" value="313-555-4321"/>
  

And here is the same config file with the connectionStrings section encrypted


  "DataProtectionConfigurationProvider">
    
      
        AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAA/NM6tBoQfE2WAlH0NVuRWQQAAAACAAAAAAAQZgAAAAEAACAAAADdZOBg8ugEiLd8RlHk95C+fuXUTC706/hDeZT2XN8G0gAAAAAOgAAAAAIAACAAAABEW5bTk3uNJDoKMt26yvD+YY1v0fqe2et8KWeJOewx3UADAADGEgVw4K4nlwQjjKpu6BZYMYXeB1eovlbYrEbg/A+Kk6UhqBTdAqt6UmW/6B4M2pXWpP9VqDTDfr7GKEK06qDdXRnYfGYH1JAg2xPoI3aeA5DQP6HAIbSymXejw/B+s47L4rTT2R4PvfRfMYiMppxCrEh+eopKdvcg34JsD+o6Il+6a4TiTiYLzQ9BESoxepfY9pqaADFrLChPYzwjymAqfsAFE/n++APjb7aktViu5+AI+QM3RDEhDFzsP7Wy+UkGsPrIoyMUaLMFNibK7LZFiBL6+VHZEur+4xyI+Uu+UH194oBOX1g77nBzuTsivNgH7048JhbzeSk9mjOZrGACX433vC6neqGaJ42sC9sC16JX9CGEZrnipeoyEeR0RT1H3A38Xasn9lYkUyE3LBIJ1k0iZJoAAnCvXfmSzXoXsHjpvmmlst3SAo24TL7WsdaVliBR/6i5N6AswTOemjvFe0Rhb5zoeGX36aI4SD71DYaLxqss1MVm5gc6CEsringGeHbFRqu/kTylA6xgr8rfL/eTcjQs2zRIUTzc4/DUSsyNIUWQ0+z+BDoR/AGTSx7v2OKp2vpmHLf7kn3DxYITlpDV6voJrbmpMx9lN3Z7DYQD4vNLczGPHpKbBCEXDHNw1E7QDrQaz38Ka4pRKnCRa/GL7X8euA82bYaJmEmUEBqhcZg3mQHR31X5tUbZ3HkvMxEUcRmJITpj29V6RKEmugkWmxl3OCJzuZ3vcUSgKnQIAJkqr3YBuZR3YJjDCo7i5EElFAcpv89rM2RtSVNC7i6KLJLsISjOgzD5CktrDjgMZLtxN6BdyljvWNj0L29APvSxd5ovxgCOKXE2UYpH3l4HgX78P82wx1vBNhO5UmqP7xdz1jTi9cGP6HHNiv8qJZjlTOO2/afnDDYt/pKJqWWTRUhJiZZipC+dQ6bBYOhMZbclROzptu0fIYwqdeDxPcXalN3kjIXW4kwblSd4TxmCO01JD9eL+MFT/PSaipj7CqaAHTnpL0n40jV4WK4EaxUTuXi0/NXBUjMFw4ZTdlEnLv1jjCKZ+r2Q1YbrrI286PATrwLDbYsVVGEefp8vBsOD7xfHmIPeYolbEOq2QAAAAHoGwcm8HT1RS0pXvgOjRR37Gy1BLfG/5xsYdZqOB9nT6xthVULhqwPlAsFwDXLfNZQLnpZiocwHDf07DeQiNK8=
      
    
  
  
    "CompanyName" value="The Awesome Company"/>
    "CompanyPhone" value="313-555-4321"/>
  

Here is a complete code snippet for getting a config and toggling the decryption of the connectionStrings section

string appName = "MyAwesomeApp.exe";
Configuration config = ConfigurationManager.OpenExeConfiguration(appName);
ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection;
if (section.SectionInformation.IsProtected)
{
    section.SectionInformation.UnprotectSection();
}
else
{
    section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
}
config.Save();

One of the nice things about using these libraries to encrypt config file sections is that we don’t need to change our code that reads the values in this section. For example, the following code

string connectionString = section.ConnectionStrings["MyApp_Dev"].ConnectionString;