C # Use and encryption of App. config for WinForm applications

Source: Internet
Author: User
Tags decrypt connectionstrings

C # Use and encryption of App. config for WinForm applications

2013-08-06 14:21:14  |  Category: Visual Studio | Tags:. NET Deployment configuration file | report | Font Size Subscribe

    

Download Lofter Client

when we write a C # application, we place an app. config in the project file, and when the program is packaged, the configuration file is automatically compiled into a. exe.config file with the same name as the assembly. The effect is that after the application is installed, you simply need to locate the file in the installation directory and change the string contents to alter the running parameters without modifying the source code. For example, you can use a configuration file to save a database connection string, display a changed text message in your application, and so on.

Because of their knowledge of how to use the method, most people choose to rebuild the configuration file themselves and manage it themselves, in fact, the file can be manipulated by the user. The app. Config file is an XML document format that allows you to add any number of strings to the file that the application can read at run time.

First, the Operation strategy

1. Add the app. Config file to the project:

Right-click the project name, choose Add → add new item, and in the Add New Item dialog box that appears, select Add Application profile, or if the project has not previously had a profile, the default file name is App. config and click OK. The app. config file that appears in Designer view is:

<?xmlversion= "1.0" encoding= "Utf-8"?>

<configuration>

</configuration>

After the project is compiled, under the Bin\debuge file, there will be two configuration files (for this project, for example), one named "JxcManagement.EXE.config" and another named "JxcManagement.vshost.exe.config ”。 The first file is the configuration file that is actually used by the project, and the changes made in the program run are saved here, and the second file is the original code "app. Config" synchronization file, which does not change during program run.

2. ConnectionStrings configuration section:

NOTE: If your SQL version is 2005 Express, the SQL Server instance named Localhost\sqlexpress is installed by default and must be changed in the following instance "Data Source=localhost;" The word "Data source=localhost\sqlexpress;", do not add an overhead grid on either side of the equals sign.

<!--database connection string--

<connectionStrings>

<clear/>

<addname= "Conjxcbook"

connectionstring= "Data source=localhost;initial Catalog=jxcbook; User id=sa;password=******** "providername=" System.Data.SqlClient "/>

</connectionStrings>

3. AppSettings configuration section:

The appsettings configuration section is a configuration for the entire program, and if it is a configuration for the current user, use the UserSettings configuration section in the same format as the following configuration writing requirements.

<!--Invoicing Management system initialization required parameters--

<appSettings>

<clear/>

<addkey= "UserName" value= ""/>

<addkey= "Password" value= ""/>

<addkey= "Department" value= ""/>

<addkey= "returnvalue" value= ""/>

<addkey= "Pwdpattern" value= ""/>

<addkey= "Userpattern" value= ""/>

</appSettings>

4. Read and Update app. Config

For read-write to the app. Config file, refer to the network article: http://www.codeproject.com/csharp/SystemConfiguration.asp titled "Read/write App. Config File with. NET 2.0 "article. Note: To access the App. Config file using the following code, you must add a reference to System.Configuration.dll in the project, in addition to the reference system.configuration.

4.1 Reading the connectionstrings configuration section

<summary>

Return data connection string based on connection string name ConnectionName

</summary>

<param name= "ConnectionName" ></param>

<returns></returns>

private static string Getconnectionstringsconfig (String connectionname)

{

string connectionString = Configurationmanager.connectionstrings[connectionname]. Connectionstring.tostring ();

Console.WriteLine (connectionString);

return connectionString;

}

4.2 Update connectionstrings configuration section

<summary>

Update connection string

</summary>

<param name= "NewName" > Connection string name </param>

<param name= "newconstring" > Connection string Contents </param>

<param name= "Newprovidername" > Data provider name </param>

private static void Updateconnectionstringsconfig (String newName,string newconstring,string Newprovidername)

{

BOOL ismodified = false; Record whether the connection string already exists

If the connection string you want to change already exists

if (configurationmanager.connectionstrings[newname]! = null) ismodified = true;

Create a new connection string instance

connectionstringsettings mysettings = New Connectionstringsettings (NewName, newconstring, newprovidername);

Open the executable configuration file *.exe.config

Configuration config = configurationmanager.openexeconfiguration (configurationuserlevel.none);

If the connection string already exists, remove it first

if (ismodified) CONFIG. ConnectionStrings.ConnectionStrings.Remove (newName);

Adds a new connection string to the configuration file.

Config. CONNECTIONSTRINGS.CONNECTIONSTRINGS.ADD (mysettings);

Save changes made to the configuration file

Config. Save (configurationsavemode.modified);

Forcing the connectionstrings configuration section of the configuration file to be re-loaded

Configurationmanager.refreshsection ("ConnectionStrings");

}

4.3 Reading the Appstrings configuration section

<summary>

Returns the value entry for the appsettings configuration section in the *.exe.config file

</summary>

<param name= "Strkey" ></param>

<returns></returns>

private static string Getappconfig (String strkey)

{

foreach (string key in Configurationmanager.appsettings)

if (key = = strkey) return Configurationmanager.appsettings[strkey];

return null;

}

4.4 Update appstrings configuration Section

<summary>

Add a pair of key, value pairs to the appsettings configuration section in the *.exe.config file

</summary>

<param name= "NewKey" ></param>

<param name= "NewValue" ></param>

private static void Updateappconfig (String newKey, String newvalue)

{

BOOL ismodified = false;

foreach (string key in Configurationmanager.appsettings)

{

if (Key==newkey)

{

IsModified = true;

}

}

Open App. Config of executable

Configuration config =

Configurationmanager.openexeconfiguration (Configurationuserlevel.none);

You need to remove the old Settings object before you can replace it

if (ismodified)

{

Config. AppSettings.Settings.Remove (NewKey);

}

ADD an application Setting.

Config. APPSETTINGS.SETTINGS.ADD (Newkey,newvalue);

Save the changes in app. Config file.

Config. Save (configurationsavemode.modified);

Force a reload of a changed section.

Configurationmanager.refreshsection ("appSettings");

}

Second, the configuration information data encryption

By default, we need to encrypt the connectionstrings fragment in the app. Config file, and the ASP. NET IIS Registration tool (Aspnet_regiis.exe) is capable of doing this, But is this tool only for ASP. NET Web. config files, can't we have a way? The answer is, of course, negative.

Configuration options

-pdf Section Webapplicationdirectory Decrypts the specified configuration section of a Web. config file in a specified physical (non-virtual) directory.

-pef Section webapplicationdirectory encrypts the specified configuration sections of a Web. config file in a specified physical (non-virtual) directory.

The-pdf and-PEF parameters are to encrypt the Web. config file in the specified physical directory, and we can rename the app. Config file to Web. config, which allows you to "cheat" the system and let it encrypt the specified configuration section. We just need to change the encrypted file name back to App. Config, so let's experiment:

First step: Rename the app. config in the directory to Web. config.

The second step: Open the SDK Command prompt, enter the command: ASPNET_REGIIS-PEF "configuration section" "Directory", for my project, for example, the config file before encryption content is as follows:

1<?xml version= "1.0" encoding= "Utf-8"?>

2<configuration>

3 <configSections>

4 <section name= "Dataconfiguration" type= " Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, version=2.0.0.0, culture=neutral, Publickeytoken=null "/>

5 </configSections>

6 <dataconfiguration defaultdatabase= "Connection String"/>

7 <connectionStrings>

8 <add name= "Connection String" connectionstring= "DATABASE=LOCOMOTIVESTAT; server=10.167.61.49; User Id=sa; Password=sa; "

9 providername= "System.Data.SqlClient"/>

Ten </connectionStrings>

11</configuration>

Input command: ASPNET_REGIIS-PEF "connectionStrings" "E:\ Development Directory", the content of the encrypted config file is as follows:

1<?xml version= "1.0" encoding= "Utf-8"?>

2<configuration>

3 <configSections>

4 <section name= "Dataconfiguration" type= " Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, version=2.0.0.0, culture=neutral, Publickeytoken=null "/>

5 </configSections>

6 <dataconfiguration defaultdatabase= "Connection String"/>

7 <connectionstrings configprotectionprovider= "RsaProtectedConfigurationProvider" >

8 <encrypteddata type= "Http://www.w3.org/2001/04/xmlenc#Element"

9 xmlns= "http://www.w3.org/2001/04/xmlenc#" >

Ten <encryptionmethod algorithm= "HTTP://WWW.W3.ORG/2001/04/XMLENC#TRIPLEDES-CBC"/>

<keyinfo xmlns= "http://www.w3.org/2000/09/xmldsig#" >

<encryptedkey xmlns= "http://www.w3.org/2001/04/xmlenc#" >

<encryptionmethod algorithm= "Http://www.w3.org/2001/04/xmlenc#rsa-1_5"/>

<keyinfo xmlns= "http://www.w3.org/2000/09/xmldsig#" >

<keyname>rsa key</keyname>

</KeyInfo>

<CipherData>

18

<ciphervalue>g2qfqqbhu1l6wupyqjadqfavhcdq/7dqcd1u9glqfei/nhdvhjqswvjnywoztqqg7q/yw7g8xlrco0h2+yyd/ Tqtnovmu/rkdjmsjzmnmnwpwq+s2vewk4u106jqwlcfbr/baf4dhvg47b9kb0jbrfxbt5v2wjvaai9u3kzuj50=</ciphervalue>

</CipherData>

</EncryptedKey>

</KeyInfo>

<CipherData>

23

<ciphervalue>blwv/zw1izfzl80yl5rkcjrijwkq0l1gjhgzbxezztgoct24ihranv3/rdcg+wiz7tl5d/ rmm7dqwkisij1sh3befg6f3+pxcw4oe1w/bovikuzjs3tokupbvttj+fscs2w/ Mwuhqawmkqwkhfs2ajt6gl6mtytb3pfqup0pdhberxoqdiaksq1zzsi1ftrti7gtt7hnpf0pjs+w9mxtvdmo/qszxfxloemis/ A5excfvr5gjpapudelusscn3xtjaixzadq3it7j+r66+l2c0xvehbt9ssg</ciphervalue>

</CipherData>

</EncryptedData>

</connectionStrings>

27</configuration>

This shows that we have completed the task, Now just change the Web. config file name back to App. config, and the. NET Framework does not need to decrypt the file in the application project, and if you want to decrypt the file it is easy to do so, enter aspnet_regiis in the SDK command prompt- PDF "configuration section" "Directory".


C # Use and encryption of App. config for WinForm applications

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.