Encrypting the Web.config in VB

I got a request for how to do the encryption of the web.config but this time in VB, so I thought I’d post it here on the blog as well. The logic is about the same, although I found that in VB I had to add a line to the configuration to save the new settings.  The code for this in vb.net (adding to the global.asax file in the “Session_Start” subroutine:

Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)


    ‘ Code that runs when a new session is started




End Sub


Private Sub EncryptSection(ByVal sSection As String)


    Dim config As Configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Context.Request.ApplicationPath)


    Dim configSection As ConfigurationSection = config.GetSection(sSection)


    If configSection.SectionInformation.IsProtected = False Then






    End If


End Sub


Comments (3)

  1. Kevin Daly says:

    I still don’t understand though why you’re doing it in Session_Start rather than Application_Start (see comment to previous entry) – I know it’s easier for testing (always a consideration with this sort of thing because of all the fun with file permissions), but in production would you really want to be performing that test every time a new Session starts?

  2. benko says:

    You could do it either way. If you were to do the encryption in Application_Start then you need to cycle the web site. Session_start ensures that the data is protected every time a new session runs.

    • Mike