部署正式環境時,web.config 中的資料庫連接字串(含帳密)若明文儲存風險極高。ASP.NET 2.0 內建 RSA 加密機制,可透過 aspnet_regiis 工具完成加密,應用程式碼**零修改**即可自動解密讀取。
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -pc "MyKeys" -exp
-pc:建立金鑰容器;-exp:允許匯出(備份/移轉用)。MyKeys 自訂。<configProtectedData>
<providers>
<add name="MyProvider"
type="System.Configuration.RsaProtectedConfigurationProvider"
keyContainerName="MyKeys"
useMachineContainer="true" />
</providers>
</configProtectedData>
建立批次檔 encrypt.bat:
@echo off
set TOOL=C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis
set APP_PATH=D:\MyWebApp
%TOOL% -pef "connectionStrings" "%APP_PATH%" -prov "MyProvider"
%TOOL% -pef "system.web/identity" "%APP_PATH%" -prov "MyProvider"
pause
-pef:加密實體路徑下的區段;-prov 指定提供者名稱。connectionStrings、system.web/identity、appSettings。加密後,須給 IIS 執行帳號(如 Network Service、IIS_IUSRS)金鑰檔讀取權限:
C:\Documents and Settings\All Users\Application Data\Microsoft\Crypto\RSA\MachineKeys\Network Service 讀取權限。缺少此步驟會拋出 The RSA key container could not be opened 錯誤。
%TOOL% -pdf "connectionStrings" "%APP_PATH%"
虛擬主機環境可改用程式碼動態加密(Configuration.GetWebConfiguration + ProtectSection),但仍需應用程式池身分有寫入 web.config 權限。