by default,Asp.net application database connection string, username and password and other sensitive information are stored in the web.config file in the root directory, we can use encryption algorithms to encrypt it,This ensures that this sensitive information is not leaked.


Asp.net application settings are usually stored in an xml file named web.config. We have modified the web.config file several times in the previous part of the tutorial. For example, in the first chapter,When we created a dataset named northwind,Database connection string information is automatically added to thenode of the web.config file. Later, in Chapter 3, we manually updated the web.config file and added aelement to all asp.net pages use datawebcontrols theme.

Since the web.config file contains sensitive information,Such as connection strings.So it is important to ensure the security of the web.config file content,This sensitive information should be hidden from unauthorized visitors.by default,Any http request for a file with a .config extension is handled by the asp.net engine,It will return the message "this type of page is not served" as shown in Figure 1. This means that visitors cannot enter "http://www.yourserver.com/web.config" in the address bar of their browser "To access your web.config file.

Figure 1:Accessing web.config through a browser will return "this type of page is not served"

But what if an attacker finds other ways to access the contents of your web.config file?What changes will he make?What steps do we take to protect this information in the web.config file?Fortunately,The vast majority of nodes in the web.config file do not contain sensitive information.What if the attacker knew the name of the default theme used by your asp.net page?

node Some nodes of the web.config file contain sensitive information,For example:connection strings, user names, passwords, server names, encryption keys, etc. We can find this information at these nodes:


This article In this article we will look at techniques to protect this sensitive information.As we will see,.net framework version 2.0 includes a protection configuration system,We can use it to easily encrypt and decrypt selected configuration nodes.

Note:At the end of this article,We will see Microsoft's advice when connecting to a database from an asp.net application.In addition to encrypting the connection string,We can also connect to a database in "safe mode" to make your system more powerful.

Step 1:Examine the protection configuration options of asp.net 2.0

asp.net 2.0 includes a protection configuration system to encrypt and decrypt configuration information.These methods are included in.The net framework can be used to programmatically encrypt and decrypt configuration information.The protection configuration system uses a provider model. It allows developers to choose which encryption to perform.

The .net framework includes 2 protected configuration providers:

.rsaprotectedconfigurationprovider:use asymmetric rsa algorithm for encryption and decryption

.dpapiprotectedconfigurationprovider:use windows data protection api (dpapi) when encrypting and decrypting

Because the protection configuration system implements the provider design mode, we can create our own protected configuration provider and apply it to our own programs.The specific process can refer to the article "implementing a protected configuration provider" ()

rsa providers and dpapi providers use "keys" for encryption and decryption. These "keys" can be stored at "machine-level" and "user-level." Keys are ideal in this case:each web application runs on its own proprietary server,Or multiple applications on a server share the same encrypted information.User-level keys are ideal security options in a shared server environment.At this time, other programs on the same server cannot decrypt your encrypted configuration information.

of The examples in this tutorial will use dpapi provider and machine-level keys.Specifically,We will encrypt thenode in the web.config file.For more information on rsa providers and user-level keys, please refer to the extended reading at the end of this article.

Note:rsaprotectedconfigurationprovider and dpapiprotectedconfigurationprovider providers are respectively compiled into rsaprotectedconfigurationprovider and dataprotectionconfigurationprovider in the machine.config file. When we encrypt or decrypt the configuration information, we need to provide the corresponding provider name (that is, rsaprotectedconfigurationprovider or dataprotectionconfigurationprovider);not the actual type name (that is, rsaprotectedconfigurationprovider and dpapiprotectedconfigurationprovider). You can do this at $windows $/microsoft.net/framework/Find the machine.config file in the version/config folder.

Step 2:Configure nodes by programming encryption and decryption

Using a certain provider, we only need a few lines of code to encrypt or decrypt a configuration node.These codes only need to reference the corresponding configuration nodes,Call its protectsection or unprotectsection method, and then call the save method to execute it.In addition, the .net framework includes a useful command line function for encryption and decryption,We will examine this feature in step 3.

For demonstration purposes,We need to create an asp.net page with buttons to facilitate encryption and decryption of thenode of the web.config file.

Open the encryptionconfigsections.aspx page in the advanceddal folder, drag a textbox control to the page,Set its id to webconfigcontents;textmode property to multiline;width and rows properties to 95%and 15. The textbox control is used to display the content of the web.config file,To see if its content is encrypted.Of course, in real-life programs,It is not possible to display the contents of the web.config file.

Add to Add two button controls below the textbox control, with the ids of encryptedconnstrings and decryptconnstrings;set their text properties to "encrypt connection strings" and "decrypt connection strings".

At this point your interface looks similar to the following:

Figure 2:Adding a textbox control and two button controls to the page

Next, when the page first logs in, we need to display the content of the web.config file in the textbox control with id webconfigcontents.Add the following code to the background class of the page,This code adds a method named displaywebconfig, in the page_load event handler,This method is called when page.ispostback is false:

protected void page_load (object sender, eventargs e)
 //on the first page visit, call displaywebconfig method
 if (! page.ispostback)
 displaywebconfig ();
private void displaywebconfig ()
 //reads in the contents of web.config and displays them in the textbox
 streamreader webconfigstream =
 file.opentext (path.combine (request.physicalapplicationpath, "web.config"));
 string configcontents=webconfigstream.readtoend ();
 webconfigstream.close ();

The displaywebconfig method calls the file class to open the web.config file of the application;calls the streamreader class to read the content into a string;Then call the path class to get the physical address of the web.config file.These 3 classes are all located in the system.io namespace.So we should add the using system.io declaration at the top of the back-end classes, or add the "system.io." Prefix in front of these classes.

Next, we need to add event handlers for the click events of these 2 buttons,Encrypt and decryptnodes using a machine-level key in a dpapi provider.In the designer,Double click on these 2 buttons to add a click event handler,Add the following code:

protected void encryptconnstrings_click (object sender, eventargs e)
 //get configuration information about web.config
 configuration config =
 webconfigurationmanager.openwebconfiguration (request.applicationpath);
 //let "s work with the<connectionstrings>section
 configurationsection connectionstrings=config.getsection ("connectionstrings");
 if (connectionstrings!=null)
 //only encrypt the section if it is not already protected
 if (! connectionstrings.sectioninformation.isprotected)
  //encrypt the<connectionstrings>section using the
  //dataprotectionconfigurationprovider provider
  connectionstrings.sectioninformation.protectsection (
  config.save ();
  //refresh the web.config display
  displaywebconfig ();
protected void decryptconnstrings_click (object sender, eventargs e)
 //get configuration information about web.config
 configuration config =
 webconfigurationmanager.openwebconfiguration (request.applicationpath);
 //let "s work with the<connectionstrings>section
 configurationsection connectionstrings =
 config.getsection ("connectionstrings");
 if (connectionstrings!=null)
 //only decrypt the section if it is protected
 if (connectionstrings.sectioninformation.isprotected)
  //decrypt the<connectionstrings>section
  connectionstrings.sectioninformation.unprotectsection ();
  config.save ();
  //refresh the web.config display
  displaywebconfig ();

Code The code of the event handler for these 2 buttons is almost the same.At the beginning, they obtain the information of the web.config file of the current application through the openwebconfiguration method of the webconfigurationmanager class. This method returns the web configuration file according to the specified valid path.Next, access thenode of the web.config file through the getsection (sectionname) method of the configuration class. This method returns a configurationsection object.

ConfigurationThe configurationsection object contains a sectioninformation property, which is used to explain other related information of the encryption node. As the code above shows,We check whether the configuration node is encrypted by looking at the isprotected property of sectioninformation.In addition, nodes can be encrypted or decrypted through the sectioninformation's protectsection (provider) and unprotectsection methods.

Protectsection (provider) method has a string type input parameter,This parameter specifies the name of the protected configuration provider used for encryption. In the event handler of the encryptconnstring button,We pass "dataprotectionconfigurationprovider" to the protectionsection (provider) method, so it indicates that the dpapi provider is used. The unprotectsection method can determine the provider used for encryption, so no input parameters are required.

After calling the protectionsection (provider) or unprotectsection method, I must also call the save method of the configuration object to perform specific operations. Once encrypted or decrypted and saved,We call the displaywebconfig method to upload the contents of the updated web.config file to the textbox control.

After typing the above code,Test the encryptionconfigsections.aspx page in your browser. At the beginning you will see that the page displays the contents of thenode of the web.config file in plain text.

Figure 3:Displaying the contents of thenode

Now click the "encrypt connection strings" button, and if "request validation" is active,When returning the page, an httprequestvalidationexception exception will be thrown, displaying a message:"a potentially dangerous request.form value was detected from the client." This request validation is active by default in asp.net 2.0,Prevents the server from accepting content that contains unencoded html. It is designed to protect the server from injection scripts.This feature can be disabled from the page or application.We disable it on this page,Validaterequest is set to false in the @page tag at the top of the page declaration code, as follows:

<%@page validaterequest="false" ...%>

After disabling this function,Click the "encrypt connection strings" button again, you can access the configuration file after the page is posted,And use the dpapi provider to encrypt thenode. The textbox control then displays the updated content of the web.config file,As shown in Figure 4, thenode's information is now encrypted.

Figure 4:Click the "encrypt connection strings" button to encrypt thenode

Before encryption,I temporarily transferred the contents of theelement:

 <ciphervalue>aqaaancmnd8bfderjhoawe/... zchw ==</ciphervalue>

Note:Theelement specifies the provider (ie dataprotection configurationprovider) used for encryption. This information will be used by the unprotectsection method when clicking the "decrypt connection strings" button.For encrypted connection strings,The system can decrypt it automatically.in short,We don't need to add any additional code to the encryptednode.Let ’s do a verification.Open the previous tutorial,For example (~/basicreporting/simpledisplay.aspx page), as shown in Figure 5, the page works as expected,This indicates that the encrypted connection string was automatically decrypted by the asp.net page.

Figure 5:The data access layer automatically decrypts the connection string information

To restore the encryptednode to plain text style,Click the "decrypt connection strings" button. After the page is posted back,You will see the connection string in the web.config file returned to plain text style.At this point, the screen looks like it was initially logged in (see Figure 3)

Step 3:Use aspnet_regiis.exe to encrypt the configuration node

.Net framework contains a lot of command line tools,These tools can be found in the $windows $/microsoft.net/framework/version/folder.With Chapter 59Use sql cache dependency sqlcachedependency"As an example, we use the aspnet_regsql.exe command line tool to add the necessary architecture to the SQL cache dependency.Another useful tool in this folder is asp.net iis registration tool (aspnet_regiis.exe). As the name implies,This asp.net iis registration tool is mainly used to register asp.net 2.0 applications on Microsoft professional web server, iis.

In addition to its attributes related to IIS,The asp.net iis registration tool can also encrypt and decrypt the configuration nodes of the web.config file. The following is the general code for using the aspnet_regiis.exe command line tool to encrypt the configuration node:

aspnet_regiis.exe -pef section physical_directory -prov provider

Where section is the configuration node to be encrypted (such as "connectionstrings");physical_directory is the full physical path of the root node of the web application;provider is the name of the protected configuration provider (such as "dataprotectionconfigurationprovider"). In addition, if you registered your web application in IIS,You can use absolute paths instead of absolute paths:

aspnet_regiis.exe -pe section -app virtual_directory -prov provider

The following is an example using aspnet_regiis.exe, which uses dpapi provider, machine-level keys,Encrypt thenode:

aspnet_regiis.exe -pef

"connectionstrings" "c:/websites/aspnet_data_tutorial_73_cs"

-prov "dataprotectionconfigurationprovider"

Similarly, the aspnet_regiis.exe command line tool can also be used to decrypt the configuration node,But we need to replace -pef with -pdf or -pd. Of course, you don't need to specify the provider name when decrypting.

aspnet_regiis.exe -pdf section physical_directory
aspnet_regiis.exe -pd section -app virtual_directory

Note:Since we are using a dpapi provider, its key is specified by the computer.So you must run the aspnet_regiis.exe tool on the same computer where the web pages are stored. For example, if you run this command line on your local computer,Then upload the encrypted connection string to another server,The server cannot decrypt it,Because the encrypted key is specified on the local computer.If you are using an rsa provider, this limitation does not exist.Because rsa provider can pass rsa keys to another computer.

Understanding database authentication options

Before any application sends a select, insert, update, or delete request to the Microsoft SQL Server database,The database first determines the identity of the requester.This process can be divided into 2 authentication modes:authentication and sql server provides:

.windows authentication:When running an asp.net application in asp.net development server in visual studio 2005,The asp.net application assumes that the identity is the currently logged in user.If running on Microsoft Internet Information Server (IIS), the asp.net application assumes the identity is domainname/machinename or domainname/network service, although these can be customized by the user.

.sql authentication:The user id and password are required for authentication. With sql authentication, the id and password can be provided by the connection string.

Windows authentication mode is generally used because it is more secure.In the windows authentication mode, the connection string does not require a username and password.And if the web server and database server are on different computers,(credentials) Authentication is not transmitted in plain text when transmitted between networks.And if it is sql authentication mode,The connection string will be hard-coded,And the authentication is transmitted in plain text format between the web server and the database server.

This tutorial uses windows authentication. We can use the connection string to see which authentication is used.The connection string for the web.config file for this tutorial is as follows:

data source =./sqlexpress;attachdbfilename=| datadirectory | /northwnd.mdf;integrated security=true;user instance=true

The term "integrated security=true" and the lack of a username and password indicate that we are using windows authentication mode. However, in some connection strings, the term "trusted connection=yes" or "integrated security=sspi" is used instead of "integrated security=true", but they all indicate that windows authentication is used.

The following code shows that sql authentication is used:


Imagine that an attacker can view the web.config file of your application. If you are using sql authentication mode to connect to the database via the internet,An attacker can use a connection string to connect to your database through sql management studio or an asp.net page on his own website.To reduce risk,We need to encrypt the connection string of the web.config file.

Note:For more information about different authentication modes in sql server, please refer to the article "building secure asp.net applications:authentication, authorization, and secure communication" ();for more examples of the differences between windows and sql authentication,See connectionstrings.com website.


by default,all in asp.net application.Files with a config suffix cannot be accessed through a browser.This is because these files may contain some sensitive information,For example:database connection string, username and password. The protection configuration system included in .net 2.0 can be protected by encrypting the specified configuration node.There are 2 built-in protected configuration providers:one uses the rsa algorithm,And the other uses windows data protection api (dpapi).

This article examines the use of dpapi provider to encrypt and decrypt configuration information.We can programmaticallyAs discussed in step 2;You can also use the aspnet_regiis.exe command line tool,As discussed in step 3.For more information on using rsa provider and user-level keys, please refer to the extension of this article.

Happy programming!

About the Author

  • Previous Sixty-six of Manipulating Data in ASPNET 20: Using Existing Stored Procedures in TableAdapters
  • Next PHP regular expression tutorial (recommended)