C# 對WinForm應用程序的App.config的使用及加密

C# 對WinForm應用程序的App.config的使用及加密  

2013-08-06 14:21:14|  分類: Visual Studio 20 |  標籤:.net  部署  配置文件  |舉報|字號 訂閱web

    

下載LOFTER客戶端數據庫

        咱們在寫C#應用程序時,在工程文件中放置一個app.config,程序打包時,系統會將該配置文件自動編譯爲與程序集同名的.exe.config 文件。做用就是應用程序安裝後,只需在安裝目錄中找到該文件,需改字符串內容,就能夠改變運行參數,而不用修改源程序代碼。例如:可使用配置文件保存數據庫鏈接字符串;在應用程序中顯示變更的文字信息等等。c#

         由於對其使用方法的不瞭解,大多數人選擇了本身重建配置文件並自行管理,實際上這個文件是能夠被用戶操做的。App.config文件爲Xml文檔格式,可在文件中添加任意數量的字符串,應用程序在運行時能夠讀取這些字符串。服務器

1、操做攻略網絡

1. 向項目添加app.config文件:app

右擊項目名稱,選擇「添加」→「添加新建項」,在出現的「添加新項」對話框中,選擇「添加應用程序配置文件」;若是項目之前沒有配置文件,則默認的文件名稱爲「app.config」,單擊「肯定」。出如今設計器視圖中的app.config文件爲:框架

<?xmlversion="1.0"encoding="utf-8" ?>ide

<configuration>工具

</configuration>加密

在項目進行編譯後,在bin\Debuge文件下,將出現兩個配置文件(以本項目爲例),一個名爲「JxcManagement.EXE.config」,另外一個名爲「JxcManagement.vshost.exe.config」。第一個文件爲項目實際使用的配置文件,在程序運行中所作的更改都將被保存於此;第二個文件爲原代碼「app.config」的同步文件,在程序運行中不會發生更改。

2. connectionStrings配置節:

請注意:若是您的SQL版本爲2005 Express版,則默認安裝時SQL服務器實例名爲localhost\SQLExpress,須更改如下實例中「Data Source=localhost;」一句爲「Data Source=localhost\SQLExpress;」,在等於號的兩邊不要加上空格。

<!--數據庫鏈接串-->

<connectionStrings>

<clear />

<addname="conJxcBook"

connectionString="Data Source=localhost;Initial Catalog=jxcbook;User ID=sa;password=********"providerName="System.Data.SqlClient" />

</connectionStrings>

3. appSettings配置節:

appSettings配置節爲整個程序的配置,若是是對當前用戶的配置,請使用userSettings配置節,其格式與如下配置書寫要求同樣。

<!--進銷存管理系統初始化須要的參數-->

<appSettings>

<clear />

<addkey="userName"value="" />

<addkey="password"value="" />

<addkey="Department"value="" />

<addkey="returnValue"value="" />

<addkey="pwdPattern"value="" />

<addkey="userPattern"value="" />

</appSettings>

4.讀取與更新app.config

對於app.config文件的讀寫,參照了網絡文章:http://www.codeproject.com/csharp/ SystemConfiguration.asp標題爲「Read/Write App.Config File with .NET 2.0」一文。請注意:要使用如下的代碼訪問app.config文件,除添加引用System.Configuration外,還必須在項目添加對System.Configuration.dll的引用。

4.1 讀取connectionStrings配置節

///<summary>

///依據鏈接串名字connectionName返回數據鏈接字符串

///</summary>

///<param name="connectionName"></param>

///<returns></returns>

private static string GetConnectionStringsConfig(string connectionName)

{

string connectionString =ConfigurationManager.ConnectionStrings[connectionName].ConnectionString.ToString();

Console.WriteLine(connectionString);

return connectionString;

}

4.2 更新connectionStrings配置節

///<summary>

///更新鏈接字符串

///</summary>

///<param name="newName">鏈接字符串名稱</param>

///<param name="newConString">鏈接字符串內容</param>

///<param name="newProviderName">數據提供程序名稱</param>

private static void UpdateConnectionStringsConfig(string newName,string newConString,string newProviderName)

{

bool isModified = false; //記錄該鏈接串是否已經存在

//若是要更改的鏈接串已經存在

if (ConfigurationManager.ConnectionStrings[newName] != null)isModified = true;

//新建一個鏈接字符串實例

ConnectionStringSettings mySettings =new ConnectionStringSettings(newName, newConString, newProviderName);

// 打開可執行的配置文件*.exe.config

Configuration config =ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

// 若是鏈接串已存在,首先刪除它

if (isModified)config.ConnectionStrings.ConnectionStrings.Remove(newName);

// 將新的鏈接串添加到配置文件中.

config.ConnectionStrings.ConnectionStrings.Add(mySettings);

// 保存對配置文件所做的更改

config.Save(ConfigurationSaveMode.Modified);

// 強制從新載入配置文件的ConnectionStrings配置節

ConfigurationManager.RefreshSection("ConnectionStrings");

}

4.3 讀取appStrings配置節

///<summary>

///返回*.exe.config文件中appSettings配置節的value項

///</summary>

///<param name="strKey"></param>

///<returns></returns>

private static string GetAppConfig(string strKey)

{

  foreach (string key in ConfigurationManager.AppSettings)

    if (key == strKey)return ConfigurationManager.AppSettings[strKey];

return null;

}

4.4 更新appStrings配置節

///<summary>

///在*.exe.config文件中appSettings配置節增長一對鍵、值對

///</summary>

///<param name="newKey"></param>

///<param name="newValue"></param>

private static void UpdateAppConfig(string newKey, string newValue)

{

bool isModified = false;

foreach (string key in ConfigurationManager.AppSettings)

{

if(key==newKey)

{

isModified = true;

}

}

// Open App.Config of executable

Configuration config =

ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

// You need to remove the old settings object before you can replace it

if (isModified)

{

config.AppSettings.Settings.Remove(newKey);

}

// Add an Application Setting.

config.AppSettings.Settings.Add(newKey,newValue);

// Save the changes in App.config file.

config.Save(ConfigurationSaveMode.Modified);

// Force a reload of a changed section.

ConfigurationManager.RefreshSection("appSettings");

}

2、對配置信息數據加密

默認狀況下,咱們須要對App.config文件裏的connectionStrings片段進行加密處理,ASP.NET IIS 註冊工具 (Aspnet_regiis.exe)能夠勝任這個工做,但這個工具只能針對ASP.NET的Web.config文件,難道咱們就沒有辦法了嗎?答案固然是否認的。

配置選項

-pdf section webApplicationDirectory對指定物理(非虛擬)目錄中的 Web.config 文件的指定配置節進行解密。

-pef section webApplicationDirectory對指定物理(非虛擬)目錄中的 Web.config 文件的指定配置節進行加密。

-pdf 和-pef 參數是對指定的物理目錄裏的Web.config文件進行加密,咱們能夠先將App.config文件更名爲Web.config,經過這兩個參數即可以「騙」過系統,讓它將指定的配置節進行加密,咱們只須要將加密後的文件名改回App.config便可,咱們來實驗一下:

    第一步:先將目錄下的App.config更名爲Web.config。

    第二步:打開SDK命令提示,輸入命令:aspnet_regiis -pef "配置節" "目錄",以個人項目爲例,加密前的config文件內容以下:

 1<?xml version="1.0" encoding="utf-8"?>

 2<configuration>

 3  <configSections>

 4    <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" />

 5  </configSections>

 6  <dataConfiguration defaultDatabase="Connection String" />

 7  <connectionStrings>

 8    <add name="Connection String" connectionString="Database=LocomotiveStat;Server=10.167.61.49;User ID=sa;Password=sa;"

 9      providerName="System.Data.SqlClient" />

10  </connectionStrings>

11</configuration>

輸入命令:aspnet_regiis -pef "connectionStrings" "E:\開發目錄",加密後的config文件內容以下:

 1<?xml version="1.0" encoding="utf-8"?>

 2<configuration>

 3  <configSections>

 4    <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" />

 5  </configSections>

 6  <dataConfiguration defaultDatabase="Connection String" />

 7  <connectionStrings configProtectionProvider="RsaProtectedConfigurationProvider">

 8    <EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element"

 9      xmlns="http://www.w3.org/2001/04/xmlenc#">

10      <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />

11      <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">

12        <EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#">

13          <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />

14          <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">

15            <KeyName>Rsa Key</KeyName>

16          </KeyInfo>

17          <CipherData>

18            

<CipherValue>g2QFQqbHU1L6WUPYqjADqFAvHcdq/7dqCd1U9GlQFEi/nHDVHjqsWvjNywOZtQQg7Q/yW7g8xlRCo0h2+yYd/tQTNoVMu/RKdJmSjZMnmnwpWq+S2VEWK4U106JQwLCfBR/bAF4DHvG47B9KB0JbRfXBt5V2wJVaAI9u3kzuj50=</CipherValue>

19          </CipherData>

20        </EncryptedKey>

21      </KeyInfo>

22      <CipherData>

23        

<CipherValue>blwV/ZW1izFZL80YL5RkcjrIjWkQ0L1gJhgZbxEzzTgOcT24ihrAnv3/rDCG+WIZ7TL5D/rMm7dQwkIsij1Sh3befg6F3+pxcW4oe1w/bovIKuzjs3tokUpBvTTj+fsCs2W/MWUhQaWMKQWkHfS2Ajt6gL6MTYtb3pfQUp0pdHbeRxoqdiAksQ1Zzsi1FtRTi7gTT7hnpF0pJs+W9mxTVDMO/qSZXfXLOEMIs/A5ExcfvR5GjpaPuDeLuSsCN3XtjaiXzaDQ3It7j+r66+L2C0xvEhbT9SsG</CipherValue>

24      </CipherData>

25    </EncryptedData>

26  </connectionStrings>

27</configuration>

    因而可知,咱們已經完成了任務,如今只須要將Web.config文件名改回App.config便可,在應用程序項目中無需對該文件進行解密操做,.NET框架會自動替咱們完成,若是想解密該文件也很簡單,在SDK命令提示裏輸入aspnet_regiis -pdf "配置節" "目錄"便可。

相關文章
相關標籤/搜索