首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在win控制台应用程序中读取加密的app.config appSettings?

如何在win控制台应用程序中读取加密的app.config appSettings?
EN

Stack Overflow用户
提问于 2014-11-23 18:08:27
回答 3查看 10.6K关注 0票数 0

编辑:这个问题没有任何意义。我把.vshost.config和exe.config混在一起了。该如何处理这些内容?

Program.cs main:

代码语言:javascript
运行
复制
databaseName = System.Configuration.ConfigurationManager.AppSettings["DatabaseName"];
databaseUser = System.Configuration.ConfigurationManager.AppSettings["DatabaseUser"];
databasePwd = System.Configuration.ConfigurationManager.AppSettings["DatabasePassword"];
port = System.Configuration.ConfigurationManager.AppSettings["Port"];
logDirectory = System.Configuration.ConfigurationManager.AppSettings["LogDirectory"];
strLogLevel = System.Configuration.ConfigurationManager.AppSettings["LogLevel"];

EncryptConfigSection("appSettings");

这是我加密文件的方式:

代码语言:javascript
运行
复制
private static void EncryptConfigSection(string sectionKey)
{
        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        ConfigurationSection section = config.GetSection(sectionKey);

        if (section != null)
        {
            if (!section.SectionInformation.IsProtected)
            {
                if (!section.ElementInformation.IsLocked)
                {
                    section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
                    section.SectionInformation.ForceSave = true;

                    config.Save(ConfigurationSaveMode.Full);
                }
            }
        }
    }

文件被复制和加密,就像我在web上找到的示例一样:

代码语言:javascript
运行
复制
<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <appSettings configProtectionProvider="DataProtectionConfigurationProvider">
        <EncryptedData>
           <CipherData>
<CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAvsQ9Wtc58EC5EZCEq91EogQAAAACAAAAAAADZgAAwAAAABAAAClVHhpR5xAw4KFNyrANtavAAAAAASAAACgAAAAEAAAABHkhg2ztiY3bdWhTG9iy6twAAAAF5mAHt7oDQWCgc1iLL2hYUJZgmquU8XsojjqXVQdV1CaW3XEBXBDhN30DEZizP3F5rGGMCjL9CVjHfsPAfvVYyRHCcup22BoByb5y/MDujaASpaWZYcdxSxLijT/Zq3zB8hiWyWPruY0G7emYEOq/xQAAADkgStCMABwo3oZx/VXHD41wrsjXg==</CipherValue>
        </CipherData>
    </EncryptedData>
</appSettings>
</configuration>

但是下一次我开始的时候,我就看不懂了。所有读取的值都为空。我很自然地从文件夹中删除了原始的未加密文件。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-11-23 23:47:27

您可以将KeyValueConfigurationCollection用于appSettings密钥,将ConnectionStringSettingsCollection用于connectionStrings密钥。

这在未加密时进行加密,在加密时解密并打印值:

代码语言:javascript
运行
复制
private static void CryptConfig (string[] sectionKeys)
{
  Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

  foreach (string sectionKey in sectionKeys)
  { 
  ConfigurationSection section = config.GetSection(sectionKey);

  if (section != null)
  {
    if (section.ElementInformation.IsLocked)
    {
      Console.WriteLine("Section: {0} is locked", sectionKey);
    }
    else
    {
      if (!section.SectionInformation.IsProtected)
      {
        //%windir%\system32\Microsoft\Protect\S-1-5-18
        section.SectionInformation.ProtectSection(DPCP);
        section.SectionInformation.ForceSave = true;
        Console.WriteLine("Encrypting: {0} {1}", section.SectionInformation.Name, section.SectionInformation.SectionName);

      }
      else
      { // display values for current config application name value pairs
        foreach (KeyValueConfigurationElement x in config.AppSettings.Settings)
        {
          Console.WriteLine("Key: {0} Value:{1}", x.Key, x.Value);
        }
        foreach (ConnectionStringSettings x in config.ConnectionStrings.ConnectionStrings)
        {
          Console.WriteLine("Name: {0} Provider:{1} Cs:{2}", x.Name, x.ProviderName, x.ConnectionString);
        }
        //
        section.SectionInformation.UnprotectSection();
        section.SectionInformation.ForceSave = true;
        Console.WriteLine("Decrypting: {0} {1}", section.SectionInformation.Name, section.SectionInformation.SectionName);
      }
    }        
  }
  else
  {
    Console.WriteLine("Section: {0} is null", sectionKey);
  }
  }
  //
  config.Save(ConfigurationSaveMode.Full);
  Console.WriteLine("Saving file: {0}", config.FilePath);      
}

使用的App.config:

代码语言:javascript
运行
复制
<?xml version="1.0" encoding="utf-8" ?>
<configuration> 
<appSettings>
<add key="DatabaseName" value="databaseName"/>
<add key="DatabaseUser" value="databaseUser"/>
<add key="DatabasePassword" value="databasePwd"/>
<add key="Port" value="port"/>
<add key="LogDirectory" value="logDirectory"/>
<add key="LogLevel" value="strLogLevel"/>   
</appSettings>
<connectionStrings>
<add name="SecurePassDataBase" connectionString="Data Source=D-xxxx;Initial Catalog=DEMO;User ID=sa;Password=******" />    
</connectionStrings>
</configuration>
票数 4
EN

Stack Overflow用户

发布于 2015-08-14 22:16:10

下面是一个非常简单的代码,您可以使用它

RsaProtectedConfigurationProvider Sample

做了一些小的修改。

代码语言:javascript
运行
复制
    static public void ProtectSection()
    {

        // Get the current configuration file.
        System.Configuration.Configuration config =
                ConfigurationManager.OpenExeConfiguration(
                ConfigurationUserLevel.None);


        // Get the section.
        ConfigurationSection section = config.GetSection("appSettings");


        // Protect (encrypt)the section.
        section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");

        // Save the encrypted section.
        section.SectionInformation.ForceSave = true;

        config.Save(ConfigurationSaveMode.Full);

        // Display decrypted configuration  
        // section. Note, the system 
        // uses the Rsa provider to decrypt 
        // the section transparently. 
        string sectionXml = section.SectionInformation.GetRawXml();

        Console.WriteLine("Decrypted section:");
        Console.WriteLine(sectionXml);

    }
票数 2
EN

Stack Overflow用户

发布于 2017-06-01 00:45:59

试试这个&你会得到你想要的:

代码语言:javascript
运行
复制
        Console.WriteLine(ConfigurationManager.OpenExeConfiguration(Path.GetFileName(Assembly.GetExecutingAssembly().CodeBase).ToString()).FilePath.ToString());

        string[] readText = File.ReadAllLines(ConfigurationManager.OpenExeConfiguration(Path.GetFileName(Assembly.GetExecutingAssembly().CodeBase).ToString()).FilePath.ToString());
        foreach (string s in readText)
        {
            Console.WriteLine(s);
        }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27087778

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档