Thursday, April 7, 2016

Programmatically Encrypt any xml Node of web.config in .Net

Suppose we have the web.config:

<connectionStrings>
    <add name="OurDb"
         connectionString="Data Source=(LocalDB)\MSSQLLocalDB;
         AttachDbFilename=|DataDirectory|\OurDb.mdf;
         Initial Catalog=OurDb;
         Integrated Security=True" 
         providerName="System.Data.SqlClient" />
  </connectionStrings>

For encrypting it, we use the code below:


public static void EncryptConnString()
 {
     Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
     ConfigurationSection section = config.GetSection("connectionStrings");

     if (!section.SectionInformation.IsProtected)
     {
         section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
         config.Save();
     }
 }

For Decrypting the same, use the below code:
public static void DecryptConnString()
 {
     Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
     ConfigurationSection section = config.GetSection("connectionStrings");
     if (section.SectionInformation.IsProtected)
     {
         section.SectionInformation.UnprotectSection();
         config.Save();
     }
 }

Sometimes you might get the following error in config.Save();:
"Failed to encrypt the section 'connectionStrings' using provider 'RsaProtectedConfigurationProvider".

To resolve this, here's the solution:
We have used the Provider RsaProtectedConfigurationProvider, you have to open the Visual Studio as Administrator.

Alternatively, we can use the other provider i.e. DataProtectionConfigurationProvider. 

Referenced from here..
     



No comments:

Post a Comment