Click here to Skip to main content
15,883,558 members
Articles / Web Development / ASP.NET

Encrypting web.config file sections

Rate me:
Please Sign up or sign in to vote.
2.63/5 (7 votes)
24 Oct 2006CPOL2 min read 63.4K   33   6
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

C#
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:

XML
<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:

XML
<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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralPlease upload sample project Pin
mymmb29-May-08 22:23
mymmb29-May-08 22:23 
GeneralRe: Please upload sample project Pin
seee sharp4-Jun-08 5:43
seee sharp4-Jun-08 5:43 
NewsTwo other related encryption articles in CodeProject ... Pin
Tony Selke27-Sep-07 7:06
Tony Selke27-Sep-07 7:06 
QuestionBad data Pin
ernestoch_cr7-Jun-07 4:20
ernestoch_cr7-Jun-07 4:20 
GeneralGood Pin
Pratik.Patel21-Nov-06 17:19
Pratik.Patel21-Nov-06 17:19 
GeneralRe: Good Pin
seee sharp23-Nov-06 1:30
seee sharp23-Nov-06 1:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.