`System.Web.Configuration` 命名空間提供 `ProtectSection` / `UnprotectSection` 方法,搭配已註冊的保護提供者(RSA/DPAPI)實現執行時期加密。
private void ProtectSection(string sectionName, string providerName) {
Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection section = config.GetSection(sectionName);
if (section != null && !section.SectionInformation.IsProtected) {
section.SectionInformation.ProtectSection(providerName);
config.Save(ConfigurationSaveMode.Modified);
}
}
private void UnprotectSection(string sectionName) {
Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection section = config.GetSection(sectionName);
if (section != null && section.SectionInformation.IsProtected) {
section.SectionInformation.UnprotectSection();
config.Save(ConfigurationSaveMode.Modified);
}
}
// 加密 appSettings
ProtectSection("appSettings", "RsaProtectedConfigurationProvider");
// 或 DPAPI:ProtectSection("appSettings", "DataProtectionConfigurationProvider")
// 解密
UnprotectSection("appSettings");
<appSettings>
<add key="name" value="shy520" />
<add key="address" value="cnblogs" />
</appSettings>
<appSettings configProtectionProvider="DataProtectionConfigurationProvider">
<EncryptedData>
<CipherData>
<CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAA...</CipherValue>
</CipherData>
</EncryptedData>
</appSettings>
| 提供者 | 加密方式 | 適用場景 | 跨機器部署 |
|---|---|---|---|
| RsaProtectedConfigurationProvider | 非對稱 RSA | Web Farm、需匯出金鑰 | 支援(匯出/匯入金鑰容器) |
| DataProtectionConfigurationProvider | DPAPI (機器/使用者層級) | 單機、簡單部署 | 不支援(綁定機器/使用者) |