Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to encrypt app.config?

Create app.config in wpf (c#)

<?xml version="1.0"?>
<configuration>
  <connectionStrings>
    <clear />
    <add name="Name"
     providerName="MySql.Data"
     connectionString="Server=.net;Uid=;Pwd=H;Database=;charset=utf8;Allow Zero Datetime=true;" />
  </connectionStrings>
</configuration>

used code C#:

    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    ConnectionStringsSection conStr = config.ConnectionStrings;
    if (!conStr.SectionInformation.IsProtected)
    {
        conStr.SectionInformation.ProtectSection("RSAProtectedConfigurationProvider");
        conStr.SectionInformation.ForceSave = true;
        config.Save();
    }
    else
    {
        foreach (ConnectionStringSettings ss in conStr.ConnectionStrings)
            Console.WriteLine(ss);
        Console.Read();
    }

config.Save(); - causes exception:

{"Failed to encrypt the section 'connectionStrings' using provider 'RsaProtectedConfigurationProvider'. The error message from the provider: Object already exists .\r\n"}

like image 619
Mediator Avatar asked Dec 01 '10 23:12

Mediator


2 Answers

I was getting the same exception on Save. By running the application as an Administrator, I was able to get around this.

I added an app.manifest file to my project, and changed the execution level like so: requestedExecutionLevel level="requireAdministrator" uiAccess="false"

This way, I always run as admin, and have permissions to save the encrypted section.

like image 179
Greg Thatcher Avatar answered Oct 13 '22 09:10

Greg Thatcher


Check the SectionInformation.ProtectSection Method

also check here

like image 29
biju Avatar answered Oct 13 '22 08:10

biju