[C#.NET][VB.NET] 保護 應用程式 組態設定 / Protect Application Configurable

  • 8848
  • 0
  • C#
  • 2009-06-11

[C#.NET][VB.NET] 保護 應用程式 組態設定 / Protect Application Configurable

此篇延續上一篇[C#.NET][VB.NET] 何謂 應用程式 組態設定 Application Configurable

1.組態設定若使用未經加密,若有權限的人讀取該檔案,裡面的敏感的內容就會由此洩露,所以加密敏感內容是必須要做的。

快照-2009414162939_thumb[3]

2.使用SectionInformation 類別中的ProtectSection方法加密,以下為ProtectSection方法所提供的Provider。

   2.1DpapiProtectedConfigurationProvider 類別

   2.2RsaProtectedConfigurationProvider 類別

3.加密後的組態檔,應用程式依然仍可正常讀取到組態檔內容,但使用其它程式卻無法直接讀取內容了。

快照-2009414163418_thumb[4]

 

4.測試時請執行"CS_AppConfig\CS_AppConfig\CS_AppConfig\bin\Debug\CS_AppConfig.exe"應用程式,並觀察"CS_AppConfig.exe.Config"是否有無變化,千萬不要用VS來讀取app.config。

5.若有寫入組態勢,別忘了要呼叫Save方法。

6.以下範例包含:如何保護組態?如何列舉區段內容?如何取得加密的Provider?

 

C#完整範例

//如何保護組態
private void button6_Click(object sender, EventArgs e)
{
    //1.引用類別開啟設定檔
    Configuration cf = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    //2.選擇保護的區段
    SectionInformation si = cf.AppSettings.SectionInformation;
    //3.判斷是否有保護
    if (si.IsProtected)
    {
        si.UnprotectSection();
        button6.Text = "保護";
    }
    else
    {
        //4.選擇保護的Provider
        si.ProtectSection("DataProtectionConfigurationProvider");
        //si.ProtectSection("RsaProtectedConfigurationProvider");
        button6.Text = "解除保護";
    }
    cf.Save(); 
 
} 
 
//如何列舉區段內容
private void button7_Click(object sender, EventArgs e)
{ 
 
    //1.將區段內容帶入集合
    NameValueCollection nvc = ConfigurationManager.AppSettings;
    Int32 con = 0;
    //2.取得集合的列舉
    IEnumerator SetIE = nvc.Keys.GetEnumerator();
    //3.顯示列舉內容
    while (SetIE.MoveNext())
    {
        Console.WriteLine("Item:{0} Value:{1}", nvc.Keys[con], nvc[con]);
        this.listBox1.Items.Add("Item:" + con + nvc.Keys[con] + " Value:" + "[" + con + "]" + nvc[con]);
        con += 1;
    } 
 
}
//如何取得加密的Provider
private void button8_Click(object sender, EventArgs e)
{
    //1.引用類別開啟設定檔
    Configuration cf = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    //2.選擇保護的區段
    SectionInformation sInfo = cf.AppSettings.SectionInformation;
    //3.取得區段的保護提供者
    ProtectedConfigurationProvider pcp = sInfo.ProtectionProvider;
    //4.判斷是否有保護
    if (pcp == null)
    {
        Console.WriteLine("Protection provider is null");
        this.listBox1.Items.Add("Protection provider is null");
    }
    else
    {
        //取得Provider
        Console.WriteLine("Protection provider: {0}", pcp.ToString());
        this.listBox1.Items.Add("provider : " + pcp.ToString());
    }
}

 

 

 

 

 

 

 

 

 

 

快照-2009414172926_thumb[3]

範例下載:

VB_AppConfig.rar

CS_AppConfig.rar

若有謬誤,煩請告知,新手發帖請多包涵


Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET

Image result for microsoft+mvp+logo