Encrypting App.Config Section and deploying to multiple machines

Viewed 3358

I've done a lot of reading around and am trying to encrypt a section in a WPF App.Config file. I am not using the default section, but rather a custom one . I have an app where the user specifices a .config file and the app reads this file in order to update keys.

In order to decrypt and encrypt my file section I am using the following code:

var configMap = new ExeConfigurationFileMap { ExeConfigFilename = this.FileName };
var config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
var configSection = config.GetSection(Section);

if (!configSection.SectionInformation.IsProtected)
   if (!configSection.ElementInformation.IsLocked)
     {
          configSection.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
          configSection.SectionInformation.ForceSave = true;
          config.Save(ConfigurationSaveMode.Full);
     }

and to Decrypt:

var configMap = new ExeConfigurationFileMap { ExeConfigFilename = this.FileName };
var config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
var configSection = config.GetSection(Section);

if (configSection.SectionInformation.IsProtected)
{
    configSection.SectionInformation.UnprotectSection();
    configSection.SectionInformation.ForceSave = true;
    config.Save(ConfigurationSaveMode.Full);
}

The problem I am facing is that if I have a file that is encrypted on Machine A and I place the file on Machine B, I cannot decrypt the .config file because the encryption was done on Machine A.

I've tried to follow the steps in several articles that recommend using aspnet_regiis to create and export key containers (link) and (link) but maybe i'm doing something wrong. My guess is that because i'm not using aspnet_regiis in order to encrypt the file or to decrypt the file I get stuck. Is there a way to do this without using the aspnet_regiis tool and the command line?

A lot of the information around is more for web.config vs app.config. Again, this is for a C#/WPF application using MVVM.

I was also looking at custom encryption (custom data provider), but all the examples i've seen are for web.config (link).

2 Answers

for winform RsaProtectedConfigurationProvider key may take system ip or hard disk number etc details to do custom key which will be different for each system and so encryption of app.config before building will not work. SO TRY TO RUN CODE to encrypt in postbuild event of exe

Related