开发者

How to Encrypt a portion of AppConfig file in any win form application?

开发者 https://www.devze.com 2023-01-06 04:13 出处:网络
I am working on a small winform application. Here i am having some configuration settings e.开发者_运维技巧g. User Name and password kinda stuff.

I am working on a small winform application. Here i am having some configuration settings e.开发者_运维技巧g. User Name and password kinda stuff.

Now my requirement is that i want to encrypt this particular detail. So can somebody tell me as how this can be done in .NET (C#).


You can use RsaProtectedConfigurationProvider http://msdn.microsoft.com/en-us/library/system.configuration.rsaprotectedconfigurationprovider.aspx


You can encrypt sections of your app.config using DPAPI provider. Put your username/pwd pair in appSettings section. Nothing else need to change in your application. you still keep reading appsettings strings as usual. Use this code below to encrypt/decrypt parts of your config file.

//call: ProtectSection("appSettings","DataProtectionConfigurationProvider"); 
private void ProtectSection(string sectionName, string provider) 
{ 
    Configuration config = 
        WebConfigurationManager. 
            OpenWebConfiguration(Request.ApplicationPath); 

    ConfigurationSection section = config.GetSection(sectionName); 

    if (section != null && !section.SectionInformation.IsProtected) 
    { 
        section.SectionInformation.ProtectSection(provider); 
        config.Save(); 
    } 
} 

//call: UnProtectSection("appSettings"); 
private void UnProtectSection(string sectionName) 
{ 
    Configuration config = 
        WebConfigurationManager. 
            OpenWebConfiguration(Request.ApplicationPath); 

    ConfigurationSection section = config.GetSection(sectionName); 

    if (section != null && section.SectionInformation.IsProtected) 
    { 
        section.SectionInformation.UnprotectSection(); 
        config.Save(); 
    } 
} 


This article on Code Project describes how to encrypt and decrypt strings. It's a class you call, but the source code is provided so you can see how it works.

This article on Sharper Tutorials actually covers the case of encrypting a connection string.

Unfortunately both are too long to quote here.


There is build-in support for encrypting configuration files for ASP.NET applications using Windows Data Protection API but I have never tried if this can be applied to App.config, too. The advantage of this is that the keys are stored in a key store under control of the operating system.

Besides this I am not aware of any other build-in solutions and we usually do decryption ourself after reading the encrypted values. This requires to store a key somewhere - usually included in the code - and is far from optimal. Therefore if possible one should use Windows integrated security (SQL Sever authentication for example is deprecated) or any other advanced infrastructure like Kerberos if available.

0

精彩评论

暂无评论...
验证码 换一张
取 消