Encrypt password to save in web.config

Published: Last Updated on 1.6K views 4 minutes read
A+A-
Reset

Once again coming back to ASP.NET series, I am back will small but useful tip if you are using forms authentication. Most of us have to publish our websites in Shared hosting environment.

Some cases might be like Application is hosted on Intranet but some people can have access to server, in such case, saving password of user data can be risky. Privacy is the most risky and concerned aspect of web (internet).

Is writing password in plain text in web.config is safe? However IIS never serve web.config file as it is but due to programming errors some time our configuration file and other codes appear on browser as they are written.

When we are saving use names and passwords in web.config instead of database   user name & passwords to access that restricted content. We are sharing a useful tip here to write an encrypted password in web.config, so we can relax and feel safe even on case of errors and can make data more secure.

Here is how our web.config file contents stored.

[xml]

[/xml]

To Encrypt the plain text, we have used built-in feature of ASP.NET framework, which is found under Web.Security namespace. Create a web form with a simple TextBox and Button to encrypt text to some unreadable value which web.config can understand and use later.

Encrypt Password-Design

Lets have a look at below design.

Front-end (ASPX) code for above design:

[html]

Encrypt Password to save in Web.Config

Password :
New Password:
All rights reserved | P.Yar.B Complex | © 2015

[/html]

Code for code-behind (ASPX.CS) page.

Add below namespace to get the required function.

using System.Web.Security;

Lets code button which will perform action.

protected void btnEncrypt_Click(object sender, EventArgs e)
 {
    if (txtPassword.Text.Length > 0 || txtPassword.Text == null || txtPassword.Text == "")
    lblHashValue.Text = FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text, "sha1");
 }

Now lets run page and put some value and click encrypt button. We will get below output.

Encrypt Password-Output

&bsp;

This is the way much secure and by default there is no way to decrypt that value to get original one. You can copy new text which is encrypted version of password and save in Web.config which will not let know anyone.
We can store the data on web.config at runtime. For detailed example and reference visit MSDN.

Related Posts

Leave a Reply

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More

Index

Adblock Detected

Please support us by disabling your AdBlocker extension from your browsers for our website.