HCL
HCL

Reputation: 36765

Encrypt Connection String in Web.Config Fails

I would like to encrypt the connection string of my web.config. Here I have found a nice example on how to do this. I implemented this and on my development machine this runs find. However if I upload it to the provider, it does not work with the following error:

[SecurityException: Request failed.] System.Configuration.DpapiProtectedConfigurationProvider.Encrypt(XmlNode node)

In this blog I have read, that this is because of the web probably runs in medium trust and therefore WebConfigurationManager.OpenWebConfiguration can not be used. Instead of this, WebConfigurationManager.GetSection should be used. However, if I get the section as proposed, the call to ProtectSection fails with the following error message:

System.InvalidOperationException: This operation does not apply at runtime

Can anyone lead me to a solution, how I can encode (and decode) the connection string in the web.config file (at runtime)?

Update
Not a real answer to the question, but the hoster gave full trust to the web and now, all worked fine. I leave the quesion open, maybe someone posts a solution to the original question and helps with this people having the same problem but not getting full trust.

Upvotes: 2

Views: 1576

Answers (1)

kbrimington
kbrimington

Reputation: 25642

From http://msdn.microsoft.com/en-us/library/89211k9b%28v=vs.80%29.aspx

static void ToggleWebEncrypt()
{
    // Open the Web.config file.
    Configuration config = WebConfigurationManager.
        OpenWebConfiguration("~");

    // Get the connectionStrings section.
    ConnectionStringsSection section =
        config.GetSection("connectionStrings")
        as ConnectionStringsSection;

    // Toggle encryption.
    if (section.SectionInformation.IsProtected)
    {
        section.SectionInformation.UnprotectSection();
    }
    else
    {
        section.SectionInformation.ProtectSection(
            "DataProtectionConfigurationProvider");
    }

    // Save changes to the Web.config file.
    config.Save();
}

UPDATE

Also, ensure that your service account has write permissions to the Web.config. Also, be aware that granting write permissions to your service account on the Web.config increases somewhat the security footprint of your application. Only do so if you understand and accept the risks.

Upvotes: 1

Related Questions