Skip to content

Instantly share code, notes, and snippets.

@TomDudfield
Created July 30, 2014 15:03
Show Gist options
  • Save TomDudfield/68dbdb69cc1e82a6e674 to your computer and use it in GitHub Desktop.
Save TomDudfield/68dbdb69cc1e82a6e674 to your computer and use it in GitHub Desktop.
AutoEncryptSettings
using System.Web;
using Security;
[assembly: WebActivatorEx.PostApplicationStartMethod(typeof(AutoEncryptApplicationSettings), "AutoEncrypt")]
namespace Security
{
public class AutoEncryptApplicationSettings : AutoEncryptSettings
{
public static void AutoEncrypt()
{
if (HttpContext.Current.IsDebuggingEnabled)
return;
Encrypt(GetConfigurationSection("appSettings"));
}
public static void Decrypt()
{
Decrypt(GetConfigurationSection("appSettings"));
}
}
}
using System.Web;
using Security;
[assembly: WebActivatorEx.PostApplicationStartMethod(typeof(AutoEncryptConnectionStrings), "AutoEncrypt")]
namespace Security
{
public class AutoEncryptConnectionStrings : AutoEncryptSettings
{
public static void AutoEncrypt()
{
if (HttpContext.Current.IsDebuggingEnabled)
return;
Encrypt(GetConfigurationSection("connectionStrings"));
}
public static void Decrypt()
{
Decrypt(GetConfigurationSection("connectionStrings"));
}
}
}
using System.Configuration;
using System.Web.Configuration;
namespace Security
{
public abstract class AutoEncryptSettings
{
protected static void Encrypt(ConfigurationSection configSection)
{
if (configSection.SectionInformation.IsProtected)
return;
configSection.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
configSection.SectionInformation.ForceSave = true;
configSection.CurrentConfiguration.Save();
}
protected static void Decrypt(ConfigurationSection configSection)
{
if (!configSection.SectionInformation.IsProtected)
return;
configSection.SectionInformation.UnprotectSection();
configSection.SectionInformation.ForceSave = true;
configSection.CurrentConfiguration.Save();
}
protected static ConfigurationSection GetConfigurationSection(string section)
{
Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~");
var configSection = configuration.GetSection(section);
if (configSection.ElementInformation.IsLocked || configSection.SectionInformation.IsLocked)
return null;
return configSection;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment