Encrypt and Decrypt connectionString section in Web.config

Here is the source code to encrypt and decrypt <connectionString> section in Web.config using RSA Protected Configuration provider model.

Note that below source code is from class library file. It is quite feasible to edit the code and use within a button click event as you wish.

Hope you find it useful!!

using System; 
using System.Collections.Generic; 
using System.Text; 
using System.Web; 
//specific to configuration 
using System.Configuration; 
using System.Web.Configuration; 
using System.Web.Security; 
namespace WebUtils 
{ 
/// <summary> 
/// Contains methods for Encrypting and decrypting connectionStrings
/// section in web.config 
/// current encryption configuration model is Rsa,
/// it is feasible to change this to DataProtectionConfigurationProvider 
/// </summary> 
/// <author>Raju Golla</author> 
public class EncryptDecrypt 
{ 
//Get Application path using HttpContext 
public static string path = HttpContext.Current.
Request.ApplicationPath; 
/// <summary> 
/// Encrypt web.config connectionStrings
/// section using Rsa protected configuration
/// provider model 
/// </summary> 
#region Encrypt method 
public static void EncryptConnString() 
{ 
Configuration config = WebConfigurationManager.
OpenWebConfiguration(path); 
ConfigurationSection section = 
config.GetSection("connectionStrings"); 
if (!section.SectionInformation.IsProtected) 
{ 
section.SectionInformation.ProtectSection
("RsaProtectedConfigurationProvider"); 
config.Save(); 
} 
} 
#endregion 
/// <summary> 
/// Decrypts connectionStrings section in 
///web.config using Rsa provider model 
/// </summary> 
#region Decrypt method 
public static void DecryptConnString() 
{ 
Configuration config = WebConfigurationManager.
OpenWebConfiguration(path); 
ConfigurationSection section = 
config.GetSection("connectionStrings"); 
if (section.SectionInformation.IsProtected) 
{ 
section.SectionInformation.UnprotectSection(); 
config.Save(); 
} 
} 
#endregion 
} 
} 

References:

http://www.beansoftware.com/ASP.NET-Tutorials/Encrypting-Connection-String.aspx

http://msdn.microsoft.com/en-us/library/ms998280.aspx

1 Comment

  • Very nice article, works nicely.

    I have used it on a commercial webhotel and it works nicely.

    I have however experienced that I had to click the decrypt button first (I have implemented the code through button click events) and then the encrypt button in order to make it work. Otherwise it would return a unauthorized error.

Comments have been disabled for this content.