12.7. Encrypting web.config Sections

Problem

You have sensitive data in your web.config file, such as the connection string used to access your database, that you do not want available in plain text.

Solution

Use the Protected Configuration feature to encrypt the sensitive information stored in web.config:

  1. Add the sensitive information to your web.config, such as a <connectionStrings> element:

    	<configuration>
    		<connectionStrings>
    			<add name="sqlConnectionString"
    				connectionString="Data Source=localhost;
    				Initial Catalog=ASPNetCookbook;
    				UID=ASPNetCookbook_User;PWD=w0rk;
    				persist security info=False;Connection Timeout=30;" />
    		</connectionStrings>
    
    		…
    
    	</configuration>
  2. Add a <machineKey> element to your web.config:

    	<configuration>
    
    		…
    		
    	  <system.web>
    		  <machineKey validationKey="AutoGenerate,IsolateApps"
    						 decryptionKey="AutoGenerate,IsolateApps" />
    	  </system.web>
    	</configuration>
  3. Run the aspnet_regiis.exe tool to encrypt the sensitive data element, such as the <connectionStrings> element with the following command:

    	aspnet_regiis -pe "connectionStrings" -app "[Your Application Name]"
  4. Run the aspnet_regiis.exe tool to encrypt the <machineKey> element:

    	aspnet_regiis -pe "system.web/machineKey" -app "[Your Application Name]"
  5. Run the aspnet_regiis.exe tool to grant access to the key container by the ASP.NET identity:

    	aspnet_regiis -pa "NetFrameworkConfigurationKey" "[ASP.NET User]"

Discussion

Applications frequently contain sensitive data in their web.config files, such as a database connection string that contains ...

Get ASP.NET 2.0 Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.