Otuyh
Otuyh

Reputation: 2474

How can i encrypt a web.config variable in c#

I have to put a password in my web.config and i need to encrypt it and use in my code, is there some tip to how to do this?

Code of my web.config:

<appSettings>
    <add key="Password" value="test123"/>
</appSettings>

How im getting it:

string Password = ConfigurationManager.AppSettings["Password"];

Thanks!

Upvotes: 1

Views: 1667

Answers (3)

Niranjan Singh
Niranjan Singh

Reputation: 18290

use FormsAuthentication.HashPasswordForStoringInConfigFile Method and store encrypt password in config file..

void HashPassword_Click(object sender, EventArgs e)
         {
            if (Page.IsValid)
            {
               string hashMethod = "";

               if (md5.Checked)
               {
                  hashMethod = "MD5";
               }
               else
               {
                  hashMethod = "SHA1";
               }

               string hashedPassword =
                  FormsAuthentication.HashPasswordForStoringInConfigFile(password.Text, hashMethod);

               result.Text = "&lt;credentials passwordFormat=\"" + hashMethod +"\"&gt;<br />" +
                  "  &lt;user name=\"" + Server.HtmlEncode(userName.Text) + "\" password=\"" +
                  hashedPassword + "\" /&gt;<br />" + "&lt;/credentials&gt;";
            }
            else
            {
               result.Text = "There was an error on the page.";
            }
         }

As you said you want to encrypt the config section check this- Encrypt sections of Web.Config or App.Config and MSDN - How to encrypt sensitive data in Machine.config and Web.config in the Security Practices: ASP.NET Security Practices at a Glance section.

Example:

copy App.Config App.Config.original
rename App.config web.config
aspnet_regiis -pef connectionStrings . -prov DataProtectionConfigurationProvider
rename web.config App.config

Upvotes: 1

rfcdejong
rfcdejong

Reputation: 2320

My tip for u: Search for ProtectedConfigurationProvider on google.

I have implemented a custom ProtectedConfigurationProvider before in our application. Searching for it on google gave me a few hits, for example http://msdn.microsoft.com/en-us/library/wfc2t3az.aspx

Upvotes: 1

Jason Lattimer
Jason Lattimer

Reputation: 2848

Check out this MSDN article on Encrypting and Decrypting Configuration Sections

Upvotes: 5

Related Questions