How to encrypt data in App.config

1

I would like to encrypt the keys (ApiKey and Secret) below in App.config:

<?xml version="1.0" encoding="utf-8" ?>
 <configuration>
  <startup> 
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
  </startup>
  <appSettings>
   <add key="ApiKey" value="sggrtdsfg"/>
   <add key="Secret" value="524524524"/>
  </appSettings>
</configuration>

I have already looked at several posts, some do by command line using "aspnet_regiis", but in my case it has to be via same code.

I created a console application, like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;

namespace CryptoTrader
{
    class Program
    {
      static void Main(string[] args)
      {
        CriptografarAppConfig();
      }

      static void CriptografarAppConfig()
      {
        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        ConfigurationSection section = config.AppSettings;

        if (!section.SectionInformation.IsProtected)
        {
           section.SectionInformation.ProtectSection("RSAProtectedConfigurationProvider");
           section.SectionInformation.ForceSave = true;
           config.Save();
        }
      }
    }
}

When the program runs, nothing happens simply! The App.config continues with the data without being encrypted, why does this occur?

Resolution: The code above works! The problem was that the App.config of the solution was not updated, but rather the CryptoTrader.exe.Config inside the CryptoTrader \ bin \ Debug folder and CryptoTrader \ bin \ Release

Source: link

    
asked by anonymous 02.07.2017 / 18:25

1 answer

0

As I researched the App.Config (or Web.Config) does not allow to persist changes at runtime and everything stays in memory, ie when the application restarts the changes are lost.

As a reference I found the answer in the English Stack link

In case of suggestion, encrypt the data and at run time retrieve the information.

If you need to do deploys or something specific you can use an approach to generate the file by a third party and change it via this other software. In this case use the xml file reading to make the necessary modifications

    
02.07.2017 / 20:26