简体   繁体   中英

Encrypt a custom section in app/web.config file

I need to encrypt/decrypt custom sections in app.config as well as web.config file. I read that aspnet_regiis can be used for web.config, but i need to do this programatically.

After opening the mappedExeConfiguration, i specify a section as follows:

ConfigurationSection connStrings = config.AppSettings;

to encrypt/decrypt the AppSettings section.

How do i specify the name of the custom section? When i type the name of my custom section after the configurationSection object, intelli-sense does not recognize it. (It only recognizes a few well known sections)

PS In my function, i need to take the custom section name as a string parameter.

Example:

eg

<Configuration>
   <MyCustomTag> 
       <... data /> 
   </MyCustomTag> 
 </Configuration>

where MyCustomTag is the section i need to encrypt/decrypt.

I achieved this by using code I found at http://www.a2zmenu.com/Blogs/CSharp/How-to-encrypt-configuration-file.aspx

I'd paste my code in, but basically it is pretty much identical to the code on that web page, except for changing the application names.

Edit: for a custom section, I'm not sure as I did not need to use it, but you could explore what the config object gives you in the following line.

Configuration config = ConfigurationManager.OpenExeConfiguration(GetAppPath() + "MyAppName.exe");

Here is my entire UpdateKey() method, which I now realise I adapted a bit from the web page. Maybe it helps.

public static void UpdateKey(string key, string newValue) 
{
    Configuration config = ConfigurationManager.OpenExeConfiguration(GetAppPath() + "MyAppName.exe");
    config.AppSettings.Settings[key].Value = newValue;
    config.Save();
} 

Then after I have saved my key(s), I call

EncryptAppSettings("appSettings");

and perhaps you can adapt the param value to suit there too.

From CommandPromt of VS 2010 call a command for encrypt:

%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis  -pef "connectionStrings" "YOUR_PROJECT_NAME" -prov "DataProtectionConfigurationProvider"

Decrypt:

%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis  -pdf "connectionStrings" "YOUR_PROJECT_NAME"

To encrypt, use the command line posted by HaGever in is answer.

This question has some example code to read app.config files from code. The code wan't working because the encryption key was not installed on the machine used to decrypt app.config.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM