加密部分外部AppSettings配置

时间:2015-03-24 12:30:00

标签: c# asp.net encryption web-config

请注意我知道这个问题
Encrypting AppSettings in file external to Web.Config

这不是一个骗局。只有在使用configSource属性链接 appSettings时,该问题才允许加密外部appSettings配置文件。我想使用file属性。所以,我在Web.config中有这样的东西:

<appSettings file="ExternalSettings.config">
    <add key="InternalSetting" value="Test123" />
</appSettings>

...和同一目录中的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

  

“无法为请求的配置对象创建配置文件。”

(顺便说一下,这段代码可以用于加密Web.config中的appSettings部分)

有没有办法加密我的ExternalSettings.config文件中的设置,但是将Web.Config文件保留为未加密?

2 个答案:

答案 0 :(得分:0)

我认为您的问题与从主要和外部配置混合密钥有关。以下定义对我来说很好:

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

外部文件中的内容

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

外部部分正确加密/解密

答案 1 :(得分:0)

是的,这是可能的。您可以使用以下代码加密配置文件的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>
    <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>

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