Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Encrypting web.config file sections

0.00/5 (No votes)
24 Oct 2006 1  
Encrypting web.config file sections in ASP.NET 2.0 with a custom provider.

Introduction

Sensitive information should not be kept as clear text. At times, we need to store sensitive information into the web.config file. To protect the information, we can encrypt it.

How to protect

To protect the information mentioned in config files, we need to encrypt the config file sections. There are providers in ASP.NET 2.0 which can be used to encrypt the information in the web.config file. We can create our own providers to take care of the encryption/decryption mechanism.

In .NET 2.0, using a command line utility, we can encrypt the information in specific sections of the web.config file.

The following command can be used to encrypt the specific sections of the web.config:

aspnet_regiis -pef "SECTION_NAME" "PHYSICAL_DIR_PATH_OF_WEB_CONFIG" 
-prov "PROVIDER"

To decrypt, you need to use the following command:

aspnet_regiis -pdf "SECTION_NAME" "PHYSICAL_DIR_PATH_OF_WEB_CONFIG" 

Note: There are sections of the web.config file which cannot be encrypted.

The following piece of code can be used to have a custom provider for encryption/decryption of web.config sections.

Code for custom provider

using System;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Xml;
public class MyProtectedConfigProvider : ProtectedConfigurationProvider
{
# region Declarations
    private TripleDESCryptoServiceProvider _cryptoProvider = 
            new TripleDESCryptoServiceProvider();

    //private RijndaelManaged _rijndaelManaged = new RijndaelManaged();
    //Any other crypto provider can be used as required.

    private string _key;
    private string _vector;
    private string _name;
# endregion
# region Properties
    /// <summary>
    /// Key for encryption/decryption
    /// </summary>
    public string Key
    {
        get { return _key; }
    }
    /// <summary>
    /// Vector for encryption/decryption
    /// </summary>
    public string Vector
    {
        get { return _vector; }
    }
    /// <summary>
    /// Name of the provider
    /// </summary>
    public override string Name
    {
        get { return _name; }
    }
# endregion
# region Overrides
    /// <summary>
    /// Provider initialization
    /// </summary>
    /// <param name="name">name of the provider</param>
    /// <param name="config">configuration parameters collection</param>
    public override void Initialize(string name, NameValueCollection config)
    {
        _name = name;
        _key = config["key"];
        _vector = config["vector"];
        _cryptoProvider.Key = HexToByte(_key);
        _cryptoProvider.IV = HexToByte(_vector);
    }
    /// <summary>
    /// Encrypt the specific Node
    /// </summary>
    /// <param name="node">XML node to encrypt</param>
    /// <returns>encrypted node</returns>
    public override XmlNode Encrypt(XmlNode node)
    {
        XmlDocument xmlDoc = new XmlDocument();
        string encryptedData = EncryptString(node.OuterXml);
        xmlDoc.PreserveWhitespace = true;
        xmlDoc.LoadXml("<EncryptedData>" +
        encryptedData +
        "</EncryptedData>");
        return xmlDoc.DocumentElement;
    }
    /// <summary>
    /// decrypt the specific node
    /// </summary>
    /// <param name="encryptedNode">Encrypted node</param>
    /// <returns>clear text xml node</returns>
    public override XmlNode Decrypt(XmlNode encryptedNode)
    {
        string decryptedData = DecryptString(encryptedNode.InnerText);
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.PreserveWhitespace = true;
        xmlDoc.LoadXml(decryptedData);
        return xmlDoc.DocumentElement;
    }
# endregion
# region Encryption/Decryption
/// <summary>
/// Encrypts the XML string
/// </summary>
/// <param name="encryptValue">clear text value</param>
/// <returns>encrypted value</returns>
    private string EncryptString(string encryptValue)
    {
        byte[] valBytes = Encoding.Unicode.GetBytes(encryptValue);
        ICryptoTransform transform = _cryptoProvider.CreateEncryptor();
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, transform, CryptoStreamMode.Write);
        cs.Write(valBytes, 0, valBytes.Length);
        cs.FlushFinalBlock();
        byte[] returnBytes = ms.ToArray();
        cs.Close();
        return Convert.ToBase64String(returnBytes);
    }
/// <summary>
/// Decrypts the text 
/// </summary>
/// <param name="encryptedValue">encrypted text</param>
/// <returns>clear text</returns>
    private string DecryptString(string encryptedValue)
    {
        byte[] valBytes = Convert.FromBase64String(encryptedValue);
        ICryptoTransform transform = _cryptoProvider.CreateDecryptor();
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, transform, CryptoStreamMode.Write);
        cs.Write(valBytes, 0, valBytes.Length);
        cs.FlushFinalBlock();
        byte[] returnBytes = ms.ToArray();
        cs.Close();
        return Encoding.Unicode.GetString(returnBytes);
    }
# endregion
# region Supporting methods
/// <summary>
/// Converts a byte array to a hexadecimal string
/// </summary>
/// <param name="byteArray">byte array</param>
/// <returns>hex string</returns>
    private string ByteToHex(byte[] byteArray)
    {
        string outString = "";
        foreach (Byte b in byteArray)
        outString += b.ToString("X2");
        return outString;
    }
/// <summary>
/// Converts a hexadecimal string to a byte array
/// </summary>
/// <param name="hexString">hex value</param>
/// <returns>byte array</returns>
    private byte[] HexToByte(string hexString)
    {
        byte[] returnBytes = new byte[hexString.Length / 2];
        for (int i = 0; i < returnBytes.Length; i++)
        returnBytes[i] =
        Convert.ToByte(hexString.Substring(i * 2, 2), 16);
        return returnBytes;
    }
# endregion
}

You need to include the following in the web.config file under the configuration node:

<configProtectedData>
<providers>
<add name="MyProtectedProvider"
    type="MyNamespace.MyProtectedConfigProvider,MyProtectedConfigProvider,
          Version=1.0.0.0, Culture=neutral, PublicKeyToken=4653ckjfie250a45e9"
    key="################################################"
    vector="################"
/>
</providers>
</configProtectedData>

Now using the command line utility and providing the name of this custom provider, we can encrypt/decrypt sections of the web.config file. The key and vector can be the same in the case of a web farm implementation, if required.

Note: This even encrypts the section which is physically in different files and referenced in the web.config file.

For example:

<appSettings configSource="configurations/appSettings.config"/>

This will go inside the appSettings file and encrypt the section.

Conclusion

This piece of code can help create your own cryptography provider to encrypt/decrypt the sections in web.config. This might be useful when you have to encrypt the sections of web.config in a Web Farm scenario. This is also helpful for using your own cryptography mechanism.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here