2009年7月6日 星期一

ASP.NET web.config 裡的 connectionStrings 加密

 

本篇主要說明利用 ASP.NET 提供的方式,製作 RSA 金鑰並加密 connectionStrings

1. 建立電腦層級 RSA 金鑰容器

aspnet_regiis -pc "MyKeys" –exp

2. 先產生一支 identity.aspx,並於 identity.aspx.cs 加入以下程式碼

protected void Page_Load(object sender, EventArgs e)
{
Response.Write(System.Security.Principal.WindowsIdentity.GetCurrent().Name);
}





執行 identity.aspx 後可能會看到 NT AUTHORITY\NETWORK SERVICE (依電腦環境有所不同)



3. 於 [命令提示字元],輸入下列指令,授與帳戶 NT AUTHORITY\NETWORK SERVICE (依電腦環境有所不同) 電腦層級 "MyKeys" RSA 金鑰容器



aspnet_regiis -pa "MyKeys" "NT AUTHORITY\NETWORK SERVICE"



4. 加入 <configProtectedData> 區段,這個區段包含名為 "MyProvider" 之 RsaProtectedConfigurationProvider 類別的執行個體,而這個執行個體使用名為 "MyKeys", 的電腦層級 RSA 金鑰容器 (如下列範例所示)。




<configuration>
<configProtectedData>
<providers>
<add name="MyProvider"
type="System.Configuration.RsaProtectedConfigurationProvider, System.Configuration, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a,
processorArchitecture=MSIL"

keyContainerName="MyKeys"
useMachineContainer="true" />
</providers>
</configProtectedData>

<connectionStrings>
<add name="SqlServices" connectionString="Data Source=localhost;Initial Catalog=Northwind;user id=sa; password=test;" />
</connectionStrings>
</configuration>





5. 對 web.config 的 connectionStrings 區段加密



aspnet_regiis -pe "connectionStrings" -app "/MyApplication" -prov "MyProvider"



6. 匯出 RSA 金鑰



aspnet_regiis -px "MyKeys" "c:\keys.xml" -pri



7. 在另一台電腦匯入 RSA 金鑰



aspnet_regiis -pi "MyKeys" "c:\keys.xml"



8. 另一台電腦需授與讀取金鑰容器的權限,依照第 3 點輸入即可。



參考資料