Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a password to Web.config and encrypt it

Tags:

asp.net

I've been all over google, MSDN, and Stack Overflow, but I can't find a full tutorial on how to do this.

I want to add a password to my Web.config file for an ASP.NET Web app, and I want to encrypt it. How do I do this?

like image 474
Jess Avatar asked Jun 22 '15 15:06

Jess


1 Answers

How to add a Web.config section and encrypt it.

You want to add a section because the aspnet_regiis will encrypt sections at a time, and you probably have config settings you don't want to encrypt.

  1. Don't use an App.config in a project. I couldn't get it to work. You will get this error message: The configuration section 'secureAppSettings' was not found. Use the Web.config in your main Web project.
  2. Create a section in your Web.config like this:

Web.config

<configSections>
  <section name="secureAppSettings" type="System.Configuration.NameValueSectionHandler" />
</configSections>
  1. Set up your new section

Web.config

<secureAppSettings>
  <add key="Password" value="1234567890"/>
</secureAppSettings>
  1. You can create a Section group. But it is optional.
  2. The section type is important. AppSettingsSection didn't work for me, but NameValueSectionHandler did.
  3. Here's the code to get the setting from the section:

C# Code

string p = ((NameValueCollection)WebConfigurationManager.GetSection("secureAppSettings"))
           ["Password"];
  1. To encrypt, run Start > Programs > Visual Studio > Visual Studio Tools > Developer Command Prompt as Administrator.
  2. Note that the following command has Case Sensitive strings, and you may need to enclose your project path with quotes. The Web.config should be INSIDE the given folder, so don't include Web.config in the command.
  3. aspnet_regiis -pef "secureAppSettings" "C:\folder\with\the_config_file"
  4. You will notice that the section in your Web.config file is now encrypted!

If you use a Web.config section of type, System.Configuration.AppSettingsSection you will probably run into this error. Could not load type 'System.Configuration.AppSettingsSection' from assembly 'System.Web' I could not get the AppSettingsSection to work.

like image 95
Jess Avatar answered Sep 28 '22 10:09

Jess