Advertisement
Willcode4cash

Encrypt connection string

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