namespace MyApp.Web.Models
{
using System.Configuration;
public static class EncryptConnection
{
public static void EncryptConnectionString(bool encrypt = false)
{
// Open the configuration file and retrieve the connectionStrings section.
var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var configSection = configFile.GetSection("connectionStrings") as ConnectionStringsSection;
if (configSection == null) return;
if ((configSection.ElementInformation.IsLocked) ||
(configSection.SectionInformation.IsLocked)) return;
// encrypt is true and section is unprotected, so encrypt
if (encrypt && !configSection.SectionInformation.IsProtected)
configSection.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
// encrypt is false and section is protected, so unencrypt
if (!encrypt && configSection.SectionInformation.IsProtected)
configSection.SectionInformation.UnprotectSection();
// re-save the configuration file section
configSection.SectionInformation.ForceSave = true;
// Save the current configuration.
configFile.Save();
}
}
}
Comments