encrypt authentication section of web.config file

Giganews Newsgroups
Subject: encrypt authentication section of web.config file
Posted by:  Dwayne (msnews08@nospam.nospam)
Date: Sun, 6 Sep 2009

I wrote a simple page to encrypt my web.config file, but I'm unable to
encrypt the authentication section.  The connectionStrings section is
encrypted, but not the authentication section.

Does anyone know why the authentication section does not get encrypted using
the code below?  I read a few articles that indicate the authentication
section can be encrypted, so I'm at a loss as why this section won't
encrypt.

I need the ability to encrypt both sections programmatically without using
the aspnet regiis.exe tool.  I need to do this with code.  Is it not
possible?

Thanks for any help.

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Web.Configuration;

public partial class admin_EncryptWebConfig : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnEncrypt_Click(object sender, EventArgs e)
    {
        ProtectSection("authentication",
"DataProtectionConfigurationProvider");
        ProtectSection("connectionStrings",
"DataProtectionConfigurationProvider");
    }

    protected void btnDecrypt_Click(object sender, EventArgs e)
    {
        UnProtectSection("authentication");
        UnProtectSection("connectionStrings");
    }

    private void ProtectSection(string sectionName, string provider)
    {
        Configuration config =
WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);

        ConfigurationSection section = config.GetSection(sectionName);

        if (section != null && !section.SectionInformation.IsProtected)
        {
            section.SectionInformation.ProtectSection(provider);
            config.Save();
        }
    }

    private void UnProtectSection(string sectionName)
    {
        Configuration config =
WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);

        ConfigurationSection section = config.GetSection(sectionName);

        if (section != null && section.SectionInformation.IsProtected)
        {
            section.SectionInformation.UnprotectSection();
            config.Save();
        }
    }
}

Replies