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

时间:2014-11-23 10:08:27

标签: c# encryption app-config

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

Program.cs main:

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

文件得到了重复和加密,就像我在网上找到的例子一样:

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

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

3 个答案:

答案 0 :(得分:4)

您可以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);      
}

使用App.config:

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

答案 1 :(得分:2)

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

RsaProtectedConfigurationProvider Sample

做了一些小改动......

    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 :(得分:0)

试试这个&amp;你会得到你想要的东西:

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