Skip to content

Instantly share code, notes, and snippets.

@kamsar
Created July 16, 2014 00:55
Show Gist options
  • Save kamsar/ef3a9f3b7ef1f9d491d5 to your computer and use it in GitHub Desktop.
Save kamsar/ef3a9f3b7ef1f9d491d5 to your computer and use it in GitHub Desktop.
Automatic web.config encryption example
using System.Configuration;
using System.Web;
using System.Web.Configuration;
using Foo.Web;
[assembly: WebActivatorEx.PostApplicationStartMethod(typeof(AutoEncryptConnectionStrings), "AutoEncrypt")]
namespace Foo.Web
{
public class AutoEncryptConnectionStrings
{
public static void AutoEncrypt()
{
// don't encrypt if debug=true in the web.config
if (HttpContext.Current.IsDebuggingEnabled) return;
var configSection = GetConfigurationSection();
if (configSection.SectionInformation.IsProtected) return;
configSection.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
configSection.SectionInformation.ForceSave = true;
configSection.CurrentConfiguration.Save();
}
public static void Decrypt()
{
var configSection = GetConfigurationSection();
if (!configSection.SectionInformation.IsProtected) return;
configSection.SectionInformation.UnprotectSection();
configSection.SectionInformation.ForceSave = true;
configSection.CurrentConfiguration.Save();
}
private static ConfigurationSection GetConfigurationSection()
{
Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~");
var configSection = configuration.GetSection("connectionStrings");
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