加密部分外部AppSettings配置

4
请注意,我知道这个问题:
Encrypting AppSettings in file external to Web.Config,但这不是重复的问题。那个问题有一个答案,允许加密外部appSettings配置文件,但前提是使用configSource属性链接appSettings。我想使用file属性。所以,我的Web.config中有这样的内容:
<appSettings file="ExternalSettings.config">
    <add key="InternalSetting" value="Test123" />
</appSettings>

在同一目录下,有一个Web.config文件和一个ExternalSettings.config文件,其中后者拥有自己的appSettings部分。运行Web应用时,两个appSettings内容将会被合并。然而,如果我只是像这样加密我的ExternalSettings.config文件:

var webConfig = WebConfigurationManager.OpenWebConfiguration("~/ExternalSettings.config");
ConfigurationSection section = webConfig.GetSection("appSettings");
if (!section.SectionInformation.IsProtected) {
    section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
    webConfig.Save();
}

我收到了一个 ConfigurationErrorsException 错误提示,内容为:

"无法为所请求的 Configuration 对象创建配置文件。"

(顺便说一下,该代码在加密只存在于 Web.config 中的 appSettings 部分方面运行良好)

有没有办法加密我的 ExternalSettings.config 文件中的设置,同时让 Web.Config 中的设置保持未加密状态?

2个回答

2

是的,这是可能的。您可以使用以下代码来加密配置文件的appSettings。

ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = "ExternalSettings.config";
Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
AppSettingsSection section = configuration.AppSettings;
if (section != null && section.SectionInformation.IsProtected == false)
{
    section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
    configuration.Save();
}

然而,这需要一个有效的配置文件而不是一个appSettings片段。因此,在运行之前,您需要将appSettings包含在一个configuration元素中。

<configuration>
    <appSettings>
        <add....
    </appSettings>
</configuration>

这将把文件转换成类似以下的内容:
<configuration>
  <appSettings configProtectionProvider="DataProtectionConfigurationProvider">
    <EncryptedData>
      <CipherData>        <CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAADx8S4qABcUakeKay9R2hvgQAAAACAAAAAAADZgAAwAAAABAAAAAyNc22wc25O41jcxXcAD8MAAAAAASAAACgAAAAEAAAAIRVbMW6KjGTFu0O8ZC1YGqIAAAAO6L8wKbLrXX4WSh+HBMPMzR1ypiWMGfC/tFS0swDwYCbBYZEXM1WU9vf3XTA/zftK+6yYLDXQ348Easx0f/a+IaZlsUvtsCJ9LSBSVM/++7JZkKrq2Zah2aQjqjn3G80XqCNc+OCNiFRhmb2ng8m3ioxC/CeOC9mVBX2qz97PIend+u4CLVBIhQAAAAsoiPgaQd9sRcFjsXQuYtTWY+qgw==</CipherValue>
      </CipherData>
    </EncryptedData>
  </appSettings>
</configuration>

一旦加密,就删除配置的开始和结束元素,运行时将像以前未加密时一样获取值。


0

我认为你的问题与主配置和外部配置混合密钥有关。以下定义对我来说运行良好:

<appSettings file="Configuration\AppSettings.config" />

外部文件中的某些内容

<appSettings>
    <!--Your configuration keys-->
</appSettings>

外部部分正确加密/解密


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接