简体   繁体   English

如何加密app.config?

[英]How to encrypt app.config?

Create app.config in wpf (c#) 在wpf中创建app.config(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#: 用过的代码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"} {“无法使用提供程序'RsaProtectedConfigurationProvider'加密'connectionStrings'部分。来自提供程序的错误消息:对象已存在。\\ r \\ n”}}

I was getting the same exception on Save. 我在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" 我在我的项目中添加了一个app.manifest文件,并改变了执行级别,如下所示:requestedExecutionLevel level =“requireAdministrator”uiAccess =“false”

This way, I always run as admin, and have permissions to save the encrypted section. 这样,我总是以管理员身份运行,并且有权保存加密部分。

You could look at using the aspnet_regiis.exe to perform encryption for you. 您可以查看使用aspnet_regiis.exe为您执行加密。 Refer to this MSDN Link 请参阅此MSDN链接

This way you could perform encryption without writing code. 这样,您无需编写代码即可执行加密。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM