Created
July 16, 2014 00:55
-
-
Save kamsar/ef3a9f3b7ef1f9d491d5 to your computer and use it in GitHub Desktop.
Automatic web.config encryption example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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