如何读取加密的应用程序.config应用程序在Win控制台应用程序中的设置

本文关键字:应用程序 Win 控制台 设置 config 何读取 读取 加密 | 更新日期: 2023-09-27 18:31:46

>编辑:这个问题毫无意义。我将.vshost.config与exe.config混合在一起。怎么办?

程序.cs主要:

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");

这是我加密文件的方式:

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 中找到的示例一样:

<?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>

但是下次我启动它时,我无法阅读它。所有读取值均为空。我自然地从文件夹中删除了原始的未加密文件。

如何读取加密的应用程序.config应用程序在Win控制台应用程序中的设置

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

这在未加密时加密

,在加密时解密并打印出值:

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);      
}

使用的应用配置:

<?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>

这里有一个非常简单的代码,你可以使用

Rsa受保护的配置提供程序示例

做了一些小的修改...

    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);
    }

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

        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);
        }