MrMistreater

Encrypt connection strings in .config file

May 9th, 2012
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.18 KB | None | 0 0
  1. public static class EncryptConnection
  2. {
  3.     public static void EncryptConnectionString(bool encrypt)
  4.     {
  5.         Configuration configFile = null;
  6.         try
  7.         {
  8.             // Open the configuration file and retrieve the connectionStrings section.
  9.             configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
  10.             ConnectionStringsSection configSection = configFile.GetSection("connectionStrings") as ConnectionStringsSection;
  11.  
  12.             if ((!(configSection.ElementInformation.IsLocked)) && (!(configSection.SectionInformation.IsLocked)))
  13.             {
  14.                 if (encrypt && !configSection.SectionInformation.IsProtected)//encrypt is false to unencrypt
  15.                 {
  16.                     configSection.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
  17.                 }
  18.  
  19.                 if (!encrypt && configSection.SectionInformation.IsProtected)//encrypt is true so encrypt
  20.                 {
  21.                     configSection.SectionInformation.UnprotectSection();
  22.                 }
  23.  
  24.                 //re-save the configuration file section
  25.                 configSection.SectionInformation.ForceSave = true;
  26.  
  27.                 // Save the current configuration.
  28.                 configFile.Save();
  29.             }              
  30.         }
  31.         catch (System.Exception ex)
  32.         {
  33.             throw (ex);
  34.         }
  35.         finally
  36.         {
  37.         }
  38.     }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment