如何 讓 桌面程式的設定檔(exe.config) 加密後, 可以在不同機器執行

情境:

客戶有一個 桌面程式(exe) 的 設定檔(exe.config) 中有連線到資料庫的帳號及密碼, 把它加密保護後, 無法在 Windows Cluster 不同結點(機器) 上移動後正常執行.

如果是在第一個結點做了加密設定, 當 Cluster 移動到第二個結點後, 程式一執行即會出現錯誤, 無法解密連線字串.

做法:

 我用一個 .NET 4.0 的 exe 測試步驟如下: 

  1. 在 Config 檔中的 <configuration> 區段 加入

 <configProtectedData >

    <providers>

        <add name="ConnectionProvider" type="System.Configuration.RsaProtectedConfigurationProvider, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" keyContainerName="connectionKey"/>

    </providers>

  </configProtectedData>

  1. 在 Server 上建立這個 key Container

             aspnet_regiis -pc "connectionKey" -exp 

  1. 授權存取帳號

            aspnet_regiis -pa "connectionFCSKey" "MachineName\LocalUser"

            or

            aspnet_regiis -pa "connectionFCSKey" "System" 

  1. 用指定 key 加密

    1. 先將 exe.config 改為 web.config
    2. aspnet_regiis.exe -pef "connectionStrings" "C:\App\Debug" -prov "ConnectionProvider”
    3. 再將 web.config 改為 exe.config 
  1. 匯出 Key

             aspnet_regiis -px "connectionKey" C:\App\keyfile.xml -pri 

  1. 到另外機器匯入 key

             aspnet_regiis -pi "connectionKey" C:\App\keyfile.xml

結果:

在兩台機器上可以正常執行同一個程式

 

參考資料:

Walkthrough: Creating and Exporting an RSA Key Containerhttps://msdn.microsoft.com/en-us/library/2w117ede.aspx

HTH. Jacky