加密配置转换

时间:2015-06-30 16:21:21

标签: c# encryption web-config app-config

我需要加密许多app和web.config文件的各个部分。我写了一个看起来像这样的小工具:

public class ConfigData
{
    public string Path { get; private set; }
    public IList<string> Sections { get; private set; }

    public ConfigData(string path, IEnumerable<string> sections)
    {
        Path = path;
        Sections = new List<string>(sections);
    }
} 

private static void EncryptDecrypt(ConfigData configData)
{
    var map = new ExeConfigurationFileMap { ExeConfigFilename = configData.Path };
    var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);

    var changesMade = false;
    foreach (var sectionName in configData.Sections)
    {
        var section = config.GetSection(sectionName);
        if (section != null && !section.ElementInformation.IsLocked)
        {
            if (section.SectionInformation.IsProtected)
            {
                section.SectionInformation.UnprotectSection();
            }
            else
            {
                section.SectionInformation.ProtectSection("MyConfigurationProvider");
            }

            section.SectionInformation.ForceSave = true;
            changesMade = true;
        }
    }

    if (changesMade)
    {
        config.Save(ConfigurationSaveMode.Full);
    }
}

这适用于标准的web和app.configs,但是当我在配置转换上运行它时,就像这样:

<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <connectionStrings>
    <add name="connection1" connectionString="myConnectionString" xdt:Transform="SetAttributes" xdt:Locator="Match(name)" />
  </connectionStrings>
</configuration>

我在var section = config.GetSection(sectionName);处出现了'xdt' is an undeclared prefix的例外情况。宣布xdt,所以我不确定如何继续。如何加密配置转换?

0 个答案:

没有答案