Asp.net
如何加密 web.config 中的一項
ASP.NET 4
我在我的網路農場的 web.config 中對連接字元串使用了RSA 密鑰加密。但是,還有一個我想加密的自定義密碼條目。在不加密其餘配置的情況下,我應該如何使用 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="foo@foo.com" /> <add key="DefaultFolder" value="789" /> </appSettings>
您可以將密碼放入單獨的部分並僅加密該部分。例如:
<?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="foo@foo.com" /> <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="foo@foo.com" /> <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"];