c# - 加密部分外部 AppSettings 配置

标签 c# asp.net encryption web-config

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

这不是骗局。该问题的答案允许对外部 appSettings 配置文件进行加密,仅当 appSettings 使用 configSource 属性链接时。我想使用 file 属性。所以,我的 Web.config 中有这样的东西:

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

... 以及位于同一目录中的 ExternalSettings.config 文件及其自己的 appSettings 部分。当我运行我的网络应用程序时,两个 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

"A configuration file cannot be created for the requested Configuration object."

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

有没有办法加密我的 ExternalSettings.config 文件中的设置,但不加密 Web.Config 的设置?

最佳答案

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

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

关于c# - 加密部分外部 AppSettings 配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29232686/

相关文章:

c# - 如何强制第三方服务尊重安全?

c# - 如何以编程方式将图像添加到 WPF 选项卡控件项

c# - 使用 float + Lambda 表达式 C#

asp.net - IIS 7 无法加载 DLL(访问被拒绝)

asp.net - CSS - 创建 9x9 数独网格的最佳方法是什么?

ssl - openssl参数和 key 生成的基本使用

c# - Double.NaN 的变量赋值变为 Double.NegativeInfinity

c# - 不确定在这种情况下如何正确使用 Matrix4.LookAt

c# - ASP.Net : DataPager Control always a step behind with paging

android - 从 Whatsapp 获取所有消息