萬盛學電腦網

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

ASP.NET 2.0 加密 Web.config 連線字串:RSA 提供者完整部署指南

加密原理

ASP.NET 2.0 引入 `` 區段,支援 `RsaProtectedConfigurationProvider` 使用非對稱加密保護敏感區段(`connectionStrings`、`system.web/identity` 等)。金鑰存放於機器層級 RSA 容器,僅授權身分可讀取。

步驟一:建立 RSA 金鑰容器

aspnet_regiis -pc "MyKeys" -exp
  • `-pc`:建立可匯出的金鑰容器
  • `-exp`:允許匯出私鑰(部署至多台伺服器時需求)

步驟二:Web.config 註冊提供者

<configuration>
  <configProtectedData>
    <providers>
      <add name="MyRsaProvider"
           type="System.Configuration.RsaProtectedConfigurationProvider, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
           keyContainerName="MyKeys"
           useMachineContainer="true" />
    </providers>
  </configProtectedData>
  <connectionStrings>...</connectionStrings>
</configuration>

步驟三:加密指定區段

aspnet_regiis -pef "connectionStrings" "C:\MyWebSite" -prov "MyRsaProvider"
aspnet_regiis -pef "system.web/identity" "C:\MyWebSite" -prov "MyRsaProvider"
  • `-pef`:加密實體路徑下的區段
  • `-prov`:指定剛建立的提供者名稱

加密後的 Web.config 範例

<connectionStrings configProtectionProvider="MyRsaProvider">
  <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>MyKeys</KeyName></KeyInfo>
        <CipherData><CipherValue>...</CipherValue></CipherData>
      </EncryptedKey>
    </KeyInfo>
    <CipherData><CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAA...</CipherValue></CipherData>
  </EncryptedData>
</connectionStrings>

步驟四:授權應用程式池身分讀取金鑰

金鑰檔位於:`C:\Documents and Settings\All Users\Application Data\Microsoft\Crypto\RSA\MachineKeys\`

    1. 依建立時間找到對應 `.xml` 檔 2. 右鍵 → 內容 → 安全性 → 新增 `NETWORK SERVICE`(IIS 6)或 `IIS_IUSRS`(IIS 7+) 3. 勾選 **讀取** 權限

缺少權限會拋出:The RSA key container could not be opened.

解密(需維護時)

aspnet_regiis -pdf "connectionStrings" "C:\MyWebSite"
aspnet_regiis -pdf "system.web/identity" "C:\MyWebSite"

多伺服器部署(Web Farm)

  1. 源機器匯出金鑰:aspnet_regiis -px "MyKeys" "C:\keys.xml" -pri
  2. 目標機器匯入:aspnet_regiis -pi "MyKeys" "C:\keys.xml"
  3. 目標機器同樣授權 `IIS_IUSRS` 讀取權限

程式碼動態加密/解密

// 加密
Configuration config = WebConfigurationManager.OpenWebConfiguration("/");
ConfigurationSection section = config.GetSection("connectionStrings");
if (!section.SectionInformation.IsProtected) {
  section.SectionInformation.ProtectSection("MyRsaProvider");
  config.Save();
}

// 解密
if (section.SectionInformation.IsProtected) {
  section.SectionInformation.UnprotectSection();
  config.Save();
}

注意事項

  • 加密後**無法在伺服器總管/設定檔編輯器**直接編輯,需解密後修改再加密
  • 虛擬主機環境若無機器層級權限,可改用 `DpapiProtectedConfigurationProvider`(使用者層級),但不支援 Web Farm
  • 定期輪換金鑰,建立新容器、重新加密、部署
copyright © 萬盛學電腦網 all rights reserved