How to encrypt app.config?

岁酱吖の 提交于 2019-12-04 21:42:40

问题


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.



来源:https://stackoverflow.com/questions/4330122/how-to-encrypt-app-config

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!