Compartir a través de


How to: Build and Run the Protected Configuration Provider Example

The topics in this section include the code for an example protected configuration provider. The example provider uses the TripleDESCryptoServiceProvider class to encrypt and decrypt configuration sections in the Web.config file.

This topic describes how to build the example and configure an ASP.NET application to use the example provider. The example protected configuration provider has been provided in Visual Basic and in C# and can be found in Protected Configuration Provider Implementation Example.

Building the Example Provider

You must encrypt Web.config file sections using the Aspnet_regiis.exe tool. Decryption can be performed either explicitly using the Aspnet_regiis.exe tool or automatically by ASP.NET at run time. Therefore, you must make the example provider type available to both the Aspnet_regiis.exe tool and to ASP.NET. This is most easily accomplished by compiling the provider with a strong name and placing it in the global assembly cache (GAC).

Note

The Strong Name tool (Sn.exe) and the Global Assembly Cache tool (Gacutil.exe) are available as part of the Windows Software Development Kit (SDK) installation. For more information, see Sn.exe (Strong Name Tool) and Gacutil.exe (Global Assembly Cache Tool).

To build the example provider

  1. At the Windows command line, run the following command:

    Sn.exe -k keys.snk
    

    This generates a strong-name key pair.

    Note

    If you cannot execute the command, you must add the .NET Framework path to the PATH variable before running the command. In Windows, right-click My Computer, click Properties, click the Advanced tab, and then click the Environment Variables button. In the System variables list, double-click the Path variable. In the Variable value text box, add a semicolon (;) to the end of the existing values in the text box, and then type the path of your .NET Framework installation. The .NET Framework is usually installed in the Windows installation folder at \Microsoft.NET\Framework\versionNumber.

  2. Create a program file named TripleDESProtectedConfigurationProvider (with the file name extension .vb or .cs, depending on what programming language you are using), and copy into it the example provider code from Protected Configuration Provider Implementation Example.

  3. Compile the provider example code and assign to the resulting assembly the strong-name key using the following command:

    vbc /out:TripleDESProtectedConfigurationProvider.dll /t:library TripleDESProtectedConfigurationProvider.vb /r:System.Configuration.dll /keyfile:keys.snk
    
    csc /out:TripleDESProtectedConfigurationProvider.dll /t:library TripleDESProtectedConfigurationProvider.cs /r:System.Configuration.dll /keyfile:keys.snk
    
  4. Install the assembly in the global assembly cache using the following command-line command:

    gacutil.exe -i TripleDESProtectedConfigurationProvider.dll
    

    Note

    If you need to remove the assembly from the GAC, you can use the Gacutil.exe tool with the following command:

    gacutil.exe -u TripleDESProtectedConfigurationProvider
    

Creating and Storing an Encryption Key

The example TripleDES protected configuration provider encrypts and decrypts configuration sections using an encryption key stored in a text file as a hexadecimal string. You create the key file using code included in the example provider. In the key file, the key is stored on the first line of the file and the vector (IV) on the second, as shown in the following example:

EBBCB17E444EBB9EA2EA7EE3E0FD9E108C6E75A90101D017
8C979426981FD2A6

After creating the key file, you should store it in a secure location on the server, and then restrict file access to the key file to the ASP.NET application identity, to the SYSTEM account, and to administrators. This protects the key from being accessed by an attacker and rendering your encryption useless.

To create an encryption key

  1. Create a console application named CreateKey.

  2. Copy the following code as the application's main module.

    Imports System
    Imports Samples.AspNet.ProtectedConfiguration
    
    Public Class CreateKey
        Public Shared Sub Main(args() As String)
        Dim filePath As String = args(0)
        Dim provider As TripleDESProtectedConfigurationProvider = _
            New TripleDESProtectedConfigurationProvider()
        provider.CreateKey(filePath)
        Console.WriteLine("New TripleDES key written to '{0}'", filePath)
      End Sub
    End Class
    
    using System;
    using Samples.AspNet.ProtectedConfiguration;
    public class CreateKey
    {
        public static void Main(string[] args)
        {
            string filePath = args[0];
            TripleDESProtectedConfigurationProvider provider = 
                new TripleDESProtectedConfigurationProvider();
            provider.CreateKey(filePath);
            Console.WriteLine("New TripleDES Key written to '{0}'", filePath);
        }
    }
    

    The example protected configuration provider includes a public CreateKey method that takes a file path as input, generates a new key, and writes the new key to the specified file. The code in the console application creates an instance of the protected configuration provider and calls its CreateKey method. The code takes a file path as a command line argument and creates a new key file in the specified location.

  3. At the Windows command line, run the console application using syntax such as the following:

    CreateKey "c:\WebSites\SampleApplication\App_Data\Keys.txt"
    

Using the Example Provider in an ASP.NET Application

After compiling the provider and creating an encryption key, you can configure an ASP.NET application to use the provider.

To use the example provider in an ASP.NET application

  1. Open your Web site's Web.config file. If the application does not have a Web.config file, create a text file named Web.config in the Web site's root folder and add the following elements:

    <?xml version="1.0"?>
    <configuration>
      <system.web>
    
      </system.web>
    </configuration>
    
  2. Within the configuration section (as a peer of the system.web element), add the following highlighted elements :

    <configuration>
    <configProtectedData><providers><add name="TripleDESProvider" type="Samples.AspNet.ProtectedConfiguration.TripleDESProtectedConfigurationProvider,TripleDESProtectedConfigurationProvider,Version=0.0.0.0, CultureInfo=neutral,PublicKeyToken=a5a9eb4fc5306403,processorArchitecture=MSIL"keyFilePath="c:\WebSites\SampleApplication\App_Data\Keys.txt" /></providers></configProtectedData>
    </configuration>
    

    Note

    Change the value of the keyFilePath attribute to match the location where you stored the key file you created earlier.

  3. Within the configuration section, add a <connectionStrings> section and one or more connection strings.

    The following example shows a connectionStrings section containing a connection string for the sample SQL Server Northwind database. The SQL Server instance name is assumed to be SampleSQLServer.

    <connectionStrings>
      <add name="NorthwindConnectionString" 
        connectionString="Data Source=SampleSQLServer;Initial Catalog=Northwind;Persist Security Info=True;" Integrated Security=SSPI;"
        providerName="System.Data.SqlClient" />
    </connectionStrings>
    

    Note

    Change the connectionString value to include connection information for the SQL Server database you want to use.

  4. Save the file and close it.

  5. At the Windows command line, run the following command to encrypt the connectionStrings section of the Web.config file:

    aspnet_regiis.exe -pe "connectionStrings" -app "/SampleApplication" -prov "TripleDESProvider"
    

    Note

    For SampleApplication, substitute the name of the Web application where you want to test the encryption.

  6. Open the Web.config file and note that the connection string has been encrypted.

  7. In the Web application, use the encrypted connection string.

    For example, add a SqlDataSource control and set its ConnectionString property to "NorthwindConnectionString," as shown in the following example:

    <asp:SqlDataSource ID="SqlDataSource1" 
      runat="server" 
      ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
      SelectCommand="SELECT ProductName FROM Products">
    </asp:SqlDataSource>
    
  8. Bind a control such as a GridView control to the SqlDataSource control.

  9. Run the page.

    Note that the data is displayed as you expect. ASP.NET has decrypted the connection string at run time before using it to connect to the Northwind database.

See Also

Concepts

Implementing a Protected Configuration Provider

Other Resources

Encrypting Configuration Information Using Protected Configuration