內建保護提供者
- DPAPI:機器專用金鑰,每台伺服器需個別加密。
- RSA:可匯出金鑰至多台伺服器,適合叢集部署(預設)。
程式化加密/解密範例
<%@ Import Namespace="System.Configuration" %>
<%@ Import Namespace="System.Web.Configuration" %>
<%@ Import Namespace="System.Xml" %>
<script runat="server" language="C#">
void ProtectButton_OnClick(Object sender, EventArgs e)
{
string path = Request.CurrentExecutionFilePath.Substring(0, Request.CurrentExecutionFilePath.LastIndexOf('/'));
Configuration config = WebConfigurationManager.OpenWebConfiguration(path);
ConfigurationSection appSettings = config.GetSection("appSettings");
if (appSettings.SectionInformation.IsProtected)
appSettings.SectionInformation.UnprotectSection();
else
appSettings.SectionInformation.ProtectSection("DataProtectionConfigurationProvider"); // 或 "RsaProtectedConfigurationProvider"
try { config.Save(); UpdateUI(); }
catch (Exception ex) { Response.Write("需授予 ASP.NET 進程帳號 web.config 寫入權限"); }
}
void UpdateUI()
{
Configuration config = WebConfigurationManager.OpenWebConfiguration(path);
ConfigurationSection appSettings = config.GetSection("appSettings");
// 顯示解密後 XML (API 自動解密)
AppSettingsXml.Text = Server.HtmlEncode(appSettings.SectionInformation.GetRawXml());
// 顯示實際加密後的 XML (直接讀檔)
XmlDocument doc = new XmlDocument(); doc.Load(Server.MapPath("web.config"));
XmlNode node = doc.SelectSingleNode("configuration/appSettings");
AppSettingsEncrypted.Text = Server.HtmlEncode(node.OuterXml);
}
</script>
加密前後對比
<!-- 加密前 -->
<appSettings>
<add key="currencyService" value="https://..." />
</appSettings>
<!-- 加密後 (使用 DPAPI) -->
<appSettings configProtectionProvider="DataProtectionConfigurationProvider">
<EncryptedData>...</EncryptedData>
</appSettings>
關鍵點
- Configuration API 讀取時自動解密,應用程式碼無需修改。
- 加密後無法用文字編輯器閱讀敏感資訊。
- 需確保 ASP.NET 進程帳號對 web.config 有寫入權限才能執行加密動作。