首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET 2.0 Web.config 連接字串加密與保護設定區段

     編輯:關於ASP.NET

內建保護提供者

  • 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 有寫入權限才能執行加密動作。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved