How to encrypt data in App.config

Asked

Viewed 371 times

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’ve looked in several posts, some do it 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! App.config continues with the data without being encrypted, why does this happen?

Resolution: The code above works! The problem was that the App.config from Solution was not updated, but Cryptotrader.exe.Config inside the folder Cryptotrader bin Debug and Cryptotrader bin Release

Source: https://stackoverflow.com/questions/8840904/app-config-are-not-saving-the-values

1 answer

0

So I searched the App.Config (or Web.Config) does not allow to persist changes at runtime and everything stays in memory, that is when the application is restarted the changes are lost.

As a reference I found the answer in Stack in English https://stackoverflow.com/questions/11149556/app-config-change-value

In the case as suggestion encrypt the data and at runtime recover the information.

If you need to deploy 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 reading of xml files to make the necessary modifications

  • Thank you William! I have updated the above resolution.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.