ASP.NET: Encrypt your applications settings
From Wiki
Summary: Encrypt your connections strings and application settings in code
You can encrypt the appSettings and connectionStrings sections of your web.config file via code when your application first starts. To do this, create a file named "global.asax" in your root directory and add this code to it:
- <%@ Application Language="VB" %>
- <%@ Import Namespace="System.Configuration" %>
- <%@ Import Namespace="System.Web.Configuration" %>
- <script runat="server">
- Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
- ' Code that runs on application startup
- ' Get the file path
- Dim path As String = HttpContext.Current.Request.CurrentExecutionFilePath
- path = path.Substring(0, path.LastIndexOf("/"))
- ' Get the appSetting and connectionStrings sections
- Dim config As System.Configuration.Configuration = WebConfigurationManager.OpenWebConfiguration(path)
- Dim appSettings As ConfigurationSection = config.GetSection("appSettings")
- Dim connectionSettings As ConfigurationSection = config.GetSection("connectionStrings")
- ' Encrypt the appSettings and connectionStrings sections if they are not already protected
- If appSettings.SectionInformation.IsProtected = False Then
- appSettings.SectionInformation.ProtectSection("DataProtectionConfigurationProvider")
- ' To unprotect this section, use:
- 'appSettings.SectionInformation.UnprotectSection()
- End If
- If connectionSettings.SectionInformation.IsProtected = False Then
- connectionSettings.SectionInformation.ProtectSection("DataProtectionConfigurationProvider")
- ' To unprotect this section, use:
- 'connectionSettings.SectionInformation.UnprotectSection()
- End If
- Try
- config.Save()
- Catch ex As Exception
- ' If an error occurs, it is most likely a permissions error
- ' so make sure the ASP.NET process account has write permissions for the web.config file
- End Try
- End Sub
- Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
- ' Code that runs on application shutdown
- End Sub
- Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
- ' Code that runs when an unhandled error occurs
- End Sub
- Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
- ' Code that runs when a new session is started
- End Sub
- Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
- ' Code that runs when a session ends.
- ' Note: The Session_End event is raised only when the sessionstate mode
- ' is set to InProc in the Web.config file. If session mode is set to StateServer
- ' or SQLServer, the event is not raised.
- End Sub
- </script>
This Hack is part of the ASP.NET Hacks collection


