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

ASP.NET Web.config 加密完整指南:RSA 保護連線字串與 appSettings 步驟詳解

     編輯:ASP.NET 基礎

為什麼要加密 Web.config

  • 連線字串包含資料庫帳號密碼、伺服器位址。
  • appSettings 可能含 API Key、金鑰、內部服務 URL。
  • 原始碼外洩、備份檔案遺失、伺服器被入侵時,敏感資訊外洩風險極高。

ASP.NET 2.0+ 內建保護機制

System.Configuration 提供 Protected Configuration Provider:

  • DPAPIProtectedConfigurationProvider:機器層級金鑰 (DPAPI),單機部署簡單,無法跨機器同步。
  • RSAProtectedConfigurationProvider:RSA 金鑰容器,可匯出/匯入,**支援 Web Farm 多機器共用金鑰**,企業級首選。

RSA 加密完整操作流程

步驟 1:建立 RSA 金鑰容器 (可匯出)


# 開啟 Developer Command Prompt for VS (管理員權限)
aspnet_regiis -pc "MyAppKeys" -exp
  • -pc:建立機器層級金鑰容器。
  • -exp:標記為可匯出 (含私鑰),否則無法匯出至其他伺服器。

步驟 2:授予應用程式集區身分讀取權限


# IIS 7.5+ 預設應用程式集區身分為 IIS AppPool\{AppPoolName}
# 查詢實際身分:在 .aspx 寫 <%= System.Security.Principal.WindowsIdentity.GetCurrent().Name %>
aspnet_regiis -pa "MyAppKeys" "IIS AppPool\MyAppPool"

# 或傳統帳號
aspnet_regiis -pa "MyAppKeys" "NT AUTHORITY\NETWORK SERVICE"

步驟 3:修改 Web.config 註冊自訂 Provider


<configuration xmlns="https://schemas.microsoft.com/.NetConfiguration/v2.0">
  <configProtectedData>
    <providers>
      <add name="MyAppRsaProvider"
           type="System.Configuration.RsaProtectedConfigurationProvider, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
           keyContainerName="MyAppKeys"
           useMachineContainer="true" />
    </providers>
  </configProtectedData>
  
  <connectionStrings configProtectionProvider="MyAppRsaProvider">
    <EncryptedData>...</EncryptedData>
  </connectionStrings>
  
  <appSettings configProtectionProvider="MyAppRsaProvider">
    <EncryptedData>...</EncryptedData>
  </appSettings>
</configuration>

步驟 4:加密指定區段


# 加密 connectionStrings
aspnet_regiis -pe "connectionStrings" -app "/MyApp" -prov "MyAppRsaProvider"

# 加密 appSettings
aspnet_regiis -pe "appSettings" -app "/MyApp" -prov "MyAppRsaProvider"

# 指定實體路徑 (非 IIS 虛擬路徑)
aspnet_regiis -pef "connectionStrings" "C:\Inetpub\wwwroot\MyApp" -prov "MyAppRsaProvider"

步驟 5:匯出金鑰部署至其他伺服器 (Web Farm)


# 來源伺服器匯出 (含私鑰,需 -exp)
aspnet_regiis -px "MyAppKeys" "C:\Keys\MyAppKeys.xml" -pri

# 複製 XML 至目標伺服器,匯入
aspnet_regiis -pi "MyAppKeys" "C:\Keys\MyAppKeys.xml" -exp

# 目標伺服器同樣授予權限
aspnet_regiis -pa "MyAppKeys" "IIS AppPool\MyAppPool"

程式碼存取加密區段 (無感解密)

ASP.NET 執行階段**自動解密**,程式碼完全不需修改:


string connStr = ConfigurationManager.ConnectionStrings["MyDb"].ConnectionString;
// 直接取得明文,框架內部自動解密
string apiKey = ConfigurationManager.AppSettings["ApiKey"];

無法加密的區段

以下區段在 configProtectedData 之前處理,**無法加密**:

  • <processModel>
  • <runtime>
  • <mscorlib>
  • <startup>
  • <system.runtime.remoting>
  • <configProtectedData> (本身)
  • <satelliteAssemblies>
  • <cryptographySettings>
  • <cryptoNameMapping>
  • <cryptoClasses>

DPAPI 替代方案 (單機部署)


# 使用預設 DPAPI Provider (機器層級)
aspnet_regiis -pe "connectionStrings" -app "/MyApp" -prov "DataProtectionConfigurationProvider"

# 或使用者層級 (需載入使用者設定檔)
aspnet_regiis -pe "connectionStrings" -app "/MyApp" -prov "DataProtectionConfigurationProvider" -pku

優點:無需管理金鑰容器。缺點:無法跨機器同步、金鑰綁定機器/使用者。

驗證加密結果

開啟 Web.config,應見類似:


<connectionStrings configProtectionProvider="MyAppRsaProvider">
  <EncryptedData Type="https://www.w3.org/2001/04/xmlenc#Element"
    xmlns="https://www.w3.org/2001/04/xmlenc#">
    <EncryptionMethod Algorithm="https://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
    <KeyInfo xmlns="https://www.w3.org/2000/09/xmldsig#">
      <EncryptedKey xmlns="https://www.w3.org/2001/04/xmlenc#">
        <EncryptionMethod Algorithm="https://www.w3.org/2001/04/xmlenc#rsa-1_5" />
        <KeyInfo><KeyName>MyAppKeys</KeyName></KeyInfo>
        <CipherData><CipherValue>...</CipherValue></CipherData>
      </EncryptedKey>
    </KeyInfo>
    <CipherData><CipherValue>...</CipherValue></CipherData>
  </EncryptedData>
</connectionStrings>

解密 (除錯/移除加密)


aspnet_regiis -pd "connectionStrings" -app "/MyApp"
aspnet_regiis -pdf "connectionStrings" "C:\Inetpub\wwwroot\MyApp"

最佳實務總結

  1. 生產環境務必使用 RSA,支援 Web Farm 擴展與金鑰輪換。
  2. 金鑰容器命名規範:AppName_Env_Keys (如 MyApp_Prod_Keys)。
  3. 金鑰備份:-px 匯出 XML 存放於離線保險庫 (HSM/加密 USB/密碼管理器)。
  4. 定期輪換金鑰:建立新容器 → 重新加密 → 部署新金鑰 → 撤銷舊金鑰權限。
  5. 應用程式集區身分最小權限:僅授予 -pa 讀取權限,不授予系統管理員。
  6. CI/CD 管線整合:部署腳本自動執行 aspnet_regiis -pef。

ASP.NET Core 現代替代方案

  • Azure Key Vault / AWS Secrets Manager / HashiCorp Vault:集中管理、自動輪換、存取稽核。
  • User Secrets (開發環境):dotnet user-secrets set。
  • 環境變數 / Docker Secrets:容器化部署標準做法。
  • 設定提供者鏈:ConfigurationBuilder 依優先序載入,敏感值不落地。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved