萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET 程式碼動態加密與解密 Web.config 區段

核心 API:ConfigurationSection.SectionInformation

`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非對稱 RSAWeb Farm、需匯出金鑰支援(匯出/匯入金鑰容器)
DataProtectionConfigurationProviderDPAPI (機器/使用者層級)單機、簡單部署不支援(綁定機器/使用者)

權限需求

  • 應用程式池身分需有金鑰容器**讀取權限**(RSA)或 DPAPI 存取權
  • 2. 程式碼執行身分需有 `Web.config` **寫入權限**(`config.Save()` 會覆寫檔案)

實務建議

  1. **部署腳本自動化**:建置管線中呼叫 `aspnet_regiis`,避免手動操作
  2. 2. **區分環境金鑰**:開發/測試/生產使用不同金鑰容器 3. **最小權限原則**:僅加密敏感區段(`connectionStrings`、`appSettings`、`system.web/identity`、`system.net/mailSettings`) 4. **備份原始設定**:加密前保留明文備份於安全位置 5. **監控異常**:`config.Save()` 可能拋出 `ConfigurationErrorsException`,需記錄日誌
copyright © 萬盛學電腦網 all rights reserved