如何在web.config中加密一个条目

问题描述 投票:41回答:3

ASP.NET 4

我已将RSA key encryption用于Web场中web.config中的连接字符串。但是,还有一个我想加密的自定义密码条目。如何在不对其余配置进行加密的情况下使用RSA密钥对其进行加密。请指教,谢谢。

示例:

  <appSettings>
        ...
    <add key="Host" value="www.foo.com" />
    <add key="Token" value="qwerqwre" />
    <add key="AccountId" value="123" />
    <add key="DepartmentId" value="456" />
    <add key="Password" value="asdfasdf" />
    <add key="SessionEmail" value="[email protected]" />
    <add key="DefaultFolder" value="789" />
  </appSettings>
asp.net encryption web-config
3个回答
61
投票

您可以将密码放在单独的部分中,并仅对该部分进行加密。例如:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="secureAppSettings" type="System.Configuration.NameValueSectionHandler, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
    </configSections>

    <appSettings>
        <add key="Host" value="www.foo.com" />
        <add key="Token" value="qwerqwre" />
        <add key="AccountId" value="123" />
        <add key="DepartmentId" value="456" />
        <add key="SessionEmail" value="[email protected]" />
        <add key="DefaultFolder" value="789" />  
    </appSettings>

    <secureAppSettings>
        <add key="Password" value="asdfasdf" />
    </secureAppSettings>  
</configuration>

然后(请注意,我在示例中使用的是DPAPI,因此请为RSA修改提供程序):

aspnet_regiis -pef secureAppSettings . -prov DataProtectionConfigurationProvider

加密后的文件将如下所示:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="secureAppSettings" type="System.Configuration.NameValueSectionHandler, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
    </configSections>

    <appSettings>
        <add key="Host" value="www.foo.com" />
        <add key="Token" value="qwerqwre" />
        <add key="AccountId" value="123" />
        <add key="DepartmentId" value="456" />
        <add key="SessionEmail" value="[email protected]" />
        <add key="DefaultFolder" value="789" />  
    </appSettings>

    <secureAppSettings configProtectionProvider="DataProtectionConfigurationProvider">
        <EncryptedData>
            <CipherData>
                <CipherValue>AQAAANCMnd.......</CipherValue>
            </CipherData>
        </EncryptedData>
    </secureAppSettings>  
</configuration>

文件加密后,您在应用程序中访问这些设置的方式仍然相同,并且完全透明:

var host = ConfigurationManager.AppSettings["Host"];
var password = ConfigurationManager.AppSettings["Password"];

12
投票

在c#和.Net 4.5中,我不得不使用它来读取加密设置:

string password = ((System.Collections.Specialized.NameValueCollection)ConfigurationManager.GetSection("secureAppSettings"))["Password"];

[但可以有效治疗。


8
投票

您无法加密单个条目-基础结构仅允许对整个配置节进行加密。

一种选择是将条目放置在其自己的配置节中并对其进行加密。

© www.soinside.com 2019 - 2024. All rights reserved.