How to encrypt app.config?

2019-03-27 20:26发布

问题:

Create app.config in wpf (c#)

<?xml version="1.0"?>
<configuration>
  <connectionStrings>
    <clear />
    <add name="Name"
     providerName="MySql.Data"
     connectionString="Server=.net;Uid=;Pwd=H;Database=;charset=utf8;Allow Zero Datetime=true;" />
  </connectionStrings>
</configuration>

used code C#:

    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    ConnectionStringsSection conStr = config.ConnectionStrings;
    if (!conStr.SectionInformation.IsProtected)
    {
        conStr.SectionInformation.ProtectSection("RSAProtectedConfigurationProvider");
        conStr.SectionInformation.ForceSave = true;
        config.Save();
    }
    else
    {
        foreach (ConnectionStringSettings ss in conStr.ConnectionStrings)
            Console.WriteLine(ss);
        Console.Read();
    }

config.Save(); - causes exception:

{"Failed to encrypt the section 'connectionStrings' using provider 'RsaProtectedConfigurationProvider'. The error message from the provider: Object already exists .\r\n"}

回答1:

Check the SectionInformation.ProtectSection Method

also check here



回答2:

I was getting the same exception on Save. By running the application as an Administrator, I was able to get around this.

I added an app.manifest file to my project, and changed the execution level like so: requestedExecutionLevel level="requireAdministrator" uiAccess="false"

This way, I always run as admin, and have permissions to save the encrypted section.



回答3:

You could look at using the aspnet_regiis.exe to perform encryption for you. Refer to this MSDN Link

This way you could perform encryption without writing code.