Thursday, December 12, 2013

How to encrypt sections in the web.config

Can be done on the command line:
http://msdn.microsoft.com/en-us/library/zhhddkxy(v=vs.100).aspx

Can also be done in code: http://weblogs.asp.net/sukumarraju/archive/2009/09/28/encrypt-and-decrypt-connectionstring-section-in-web-config.aspx


one thing that was a little confusing is that you need to pass the site name and not the web.config file location. So for a site called MySite under the root, you need to pass "\MySite" to the function...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Web.Configuration;

namespace WindowsFormsApplication1
{
    public static class EncryptConfiguration
    {
        private const string ProtectedConfigurationProvider = "RsaProtectedConfigurationProvider";
        private const string ConnectionStringsSection = "connectionStrings";

        public static bool EncryptConnectionString(string site)
        {
            try
            {                
                Configuration config = WebConfigurationManager.OpenWebConfiguration(site);
                ConfigurationSection connectionStringSection = config.GetSection(ConnectionStringsSection);
                
                if (!connectionStringSection.SectionInformation.IsProtected)
                {
                    // encrypt it here
                    connectionStringSection.SectionInformation.ProtectSection(ProtectedConfigurationProvider);
                    config.Save(ConfigurationSaveMode.Full);                    
                }
                return true;
            }
            catch (Exception ex)
            {
                // log the error here
                return false;
            }            
        }

        public static bool DeCryptConnectionStringSection(string site)
        {
            try
            {
                Configuration config = WebConfigurationManager.OpenWebConfiguration(site);
                ConfigurationSection connectionStringSection = config.GetSection(ConnectionStringsSection);
                if (connectionStringSection.SectionInformation.IsProtected)
                {
                    connectionStringSection.SectionInformation.UnprotectSection();
                    config.Save();
                }
                return true;
            }
            catch (Exception ex)
            {
                // log the error here
                return false;
            }
        }
    }
}

No comments: