ProtectedConfigurationProvider Class (System.Configuration)

Switch View :
ScriptFree
.NET Framework Class Library
ProtectedConfigurationProvider Class

Note: This class is new in the .NET Framework version 2.0.

Is the base class to create providers for encrypting and decrypting protected-configuration data.

Namespace: System.Configuration
Assembly: System.Configuration (in system.configuration.dll)

Syntax

Visual Basic (Declaration)
Public MustInherit Class ProtectedConfigurationProvider
	Inherits ProviderBase
Visual Basic (Usage)
Dim instance As ProtectedConfigurationProvider

C#
public abstract class ProtectedConfigurationProvider : ProviderBase
C++
public ref class ProtectedConfigurationProvider abstract : public ProviderBase
J#
public abstract class ProtectedConfigurationProvider extends ProviderBase
JScript
public abstract class ProtectedConfigurationProvider extends ProviderBase
Remarks

You can encrypt sections of a configuration file to protect sensitive information used by your application. This improves security by making it difficult for unauthorized access even if an attacker gains access to your configuration file.

The .NET Framework includes two protected-configuration providers that can be used to encrypt sections of a configuration file, the RSAProtectedConfigurationProvider, which uses the RSACryptoServiceProvider to encrypt configuration sections, and the DPAPIProtectedConfigurationProvider, which uses the Windows Data Protection API (DPAPI) to encrypt configuration sections.

You may have a requirement to encrypt sensitive information using an algorithm other than the RSA or DPAPI providers. In this case, you can build your own custom protected-configuration provider. The ProtectedConfigurationProvider is an abstract base class that you must inherit from to create your own protected-configuration provider.

Whether you use a standard or a custom provider, you must ensure that it is configured with the add element in the providers section of the configProtectedData configuration section. (See next example.)

For details, see Implementing a Protected Configuration Provider.

NoteNote

When ASP.NET encounters encrypted configuration data, it performs decryption transparently using the configured provider. No action is required on your side other than making sure that you configure the required provider.

Example

The following example shows how to implement a custom ProtectedConfigurationProvider.

To be able to configure this provider, as shown in the next configuration excerpt, you must install it in the Global Assembly Cache (GAC). Refer to Implementing a Protected Configuration Provider for more information.

Visual Basic
Imports System
Imports System.Xml
Imports System.Security.Cryptography
Imports System.IO
Imports System.Text
Imports System.Configuration.Provider
Imports System.Collections.Specialized
Imports System.Configuration


' Show how to use the ProtectedConfigurationProvider
' to create a custom protected configuration
' provider.

Public Class TripleDESProtectedConfigurationProvider
   Inherits ProtectedConfigurationProvider
   
    Private des _
    As New TripleDESCryptoServiceProvider()
   
   Private pKeyFilePath As String
   Private pName As String
   
   ' Gets the path of the file
   ' containing the key used to
   ' encrypt/decrypt.
   
   Public ReadOnly Property KeyFilePath() As String
      Get
         Return pKeyFilePath
      End Get
   End Property 
   
   ' Gets the provider name.
   
   Public Overrides ReadOnly Property Name() As String
      Get
         Return pName
      End Get
   End Property
    
   
   ' Performs provider initialization.
    Public Overrides Sub Initialize( _
    ByVal name As String, _
    ByVal config As NameValueCollection)
        pName = name
        pKeyFilePath = config("keyContainerName")
        ReadKey(KeyFilePath)
    End Sub 'Initialize
   
   
   ' Performs encryption.
    Public Overrides Function Encrypt( _
    ByVal node As XmlNode) As XmlNode
        Dim encryptedData As String = _
        EncryptString(node.OuterXml)

        Dim xmlDoc As New XmlDocument()
        xmlDoc.PreserveWhitespace = True
        xmlDoc.LoadXml( _
        ("<EncryptedData>" + encryptedData + _
        "</EncryptedData>"))

        Return xmlDoc.DocumentElement
    End Function 'Encrypt

   ' Performs decryption.
    Public Overrides Function Decrypt( _
    ByVal encryptedNode As XmlNode) As XmlNode
        Dim decryptedData As String = _
        DecryptString(encryptedNode.InnerText)

        Dim xmlDoc As New XmlDocument()
        xmlDoc.PreserveWhitespace = True
        xmlDoc.LoadXml(decryptedData)

        Return xmlDoc.DocumentElement
    End Function 'Decrypt

   
   
   ' Encrypts a configuration section and returns 
   ' the encrypted XML as a string.
    Private Function EncryptString( _
    ByVal encryptValue As String) As String
        Dim valBytes As Byte() = _
        Encoding.Unicode.GetBytes(encryptValue)

        Dim transform As ICryptoTransform = _
        des.CreateEncryptor()

        Dim ms As New MemoryStream()
        Dim cs As New CryptoStream(ms, _
        transform, CryptoStreamMode.Write)
        cs.Write(valBytes, 0, valBytes.Length)
        cs.FlushFinalBlock()
        Dim returnBytes As Byte() = ms.ToArray()
        cs.Close()

        Return Convert.ToBase64String(returnBytes)
    End Function 'EncryptString
   
   
   
   ' Decrypts an encrypted configuration section and 
   ' returns the unencrypted XML as a string.
    Private Function DecryptString( _
    ByVal encryptedValue As String) As String
        Dim valBytes As Byte() = _
        Convert.FromBase64String(encryptedValue)

        Dim transform As ICryptoTransform = _
        des.CreateDecryptor()

        Dim ms As New MemoryStream()
        Dim cs As New CryptoStream(ms, _
        transform, CryptoStreamMode.Write)
        cs.Write(valBytes, 0, valBytes.Length)
        cs.FlushFinalBlock()
        Dim returnBytes As Byte() = ms.ToArray()
        cs.Close()

        Return Encoding.Unicode.GetString(returnBytes)
    End Function 'DecryptString
   
   
   ' Generates a new TripleDES key and vector and 
   ' writes them to the supplied file path.
   Public Sub CreateKey(filePath As String)
      des.GenerateKey()
      des.GenerateIV()
      
      Dim sw As New StreamWriter(filePath, False)
      sw.WriteLine(ByteToHex(des.Key))
      sw.WriteLine(ByteToHex(des.IV))
      sw.Close()
   End Sub 'CreateKey
   
   
   
   ' Reads in the TripleDES key and vector from 
   ' the supplied file path and sets the Key 
   ' and IV properties of the 
   ' TripleDESCryptoServiceProvider.
   Private Sub ReadKey(filePath As String)
      Dim sr As New StreamReader(filePath)
      Dim keyValue As String = sr.ReadLine()
      Dim ivValue As String = sr.ReadLine()
      des.Key = HexToByte(keyValue)
      des.IV = HexToByte(ivValue)
   End Sub 'ReadKey
   
   
   
   ' Converts a byte array to a hexadecimal string.
    Private Function ByteToHex( _
    ByVal byteArray() As Byte) As String
        Dim outString As String = ""

        Dim b As [Byte]
        For Each b In byteArray
            outString += b.ToString("X2")
        Next b
        Return outString
    End Function 'ByteToHex
   
   
   ' Converts a hexadecimal string to a byte array.
   Private Function HexToByte(hexString As String) As Byte()
      Dim returnBytes(hexString.Length / 2) As Byte
      Dim i As Integer
      For i = 0 To returnBytes.Length - 1
            returnBytes(i) = _
            Convert.ToByte(hexString.Substring(i * 2, 2), 16)
      Next i
      Return returnBytes
   End Function 'HexToByte
End Class 'TripleDESProtectedConfigurationProvider 


C#
using System;
using System.Xml;
using System.Security.Cryptography;
using System.IO;
using System.Text;
using System.Configuration.Provider;
using System.Collections.Specialized;
using System.Configuration;

namespace Samples.AspNet.Configuration
{
    // Show how to use the ProtectedConfigurationProvider
    // to create a custom protected configuration
    // provider.
    public class TripleDESProtectedConfigurationProvider :
        ProtectedConfigurationProvider
    {

        private TripleDESCryptoServiceProvider des =
            new TripleDESCryptoServiceProvider();

        private string pKeyFilePath;
        private string pName;

        // Gets the path of the file
        // containing the key used to
        // encrypt/decrypt.
        public string KeyFilePath
        {
            get { return pKeyFilePath; 
        


        // Gets the provider name.
        public override string Name
        {
            get { return pName; 
        


        // Performs provider initialization.
        public override void Initialize(string name,
            NameValueCollection config)
        {
            pName = name;
            pKeyFilePath = config["keyContainerName"];
            ReadKey(KeyFilePath);
        


        // Performs encryption.
        public override XmlNode Encrypt(XmlNode node)
        {
            string encryptedData = EncryptString(node.OuterXml);

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.PreserveWhitespace = true;
            xmlDoc.LoadXml("<EncryptedData>" +
                encryptedData + "</EncryptedData>");

            return xmlDoc.DocumentElement;
        

        // Performs decryption.
        public override XmlNode Decrypt(XmlNode encryptedNode)
        {
            string decryptedData =
                DecryptString(encryptedNode.InnerText);

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.PreserveWhitespace = true;
            xmlDoc.LoadXml(decryptedData);

            return xmlDoc.DocumentElement;
        

        // Encrypts a configuration section and returns 
        // the encrypted XML as a string.
        private string EncryptString(string encryptValue)
        {
            byte[] valBytes =
                Encoding.Unicode.GetBytes(encryptValue);

            ICryptoTransform transform = des.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);
        


        // Decrypts an encrypted configuration section and 
        // returns the unencrypted XML as a string.
        private string DecryptString(string encryptedValue)
        {
            byte[] valBytes =
                Convert.FromBase64String(encryptedValue);

            ICryptoTransform transform = des.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);
        

        // Generates a new TripleDES key and vector and 
        // writes them to the supplied file path.
        public void CreateKey(string filePath)
        {
            des.GenerateKey();
            des.GenerateIV();

            StreamWriter sw = new StreamWriter(filePath, false);
            sw.WriteLine(ByteToHex(des.Key));
            sw.WriteLine(ByteToHex(des.IV));
            sw.Close();
        


        // Reads in the TripleDES key and vector from 
        // the supplied file path and sets the Key 
        // and IV properties of the 
        // TripleDESCryptoServiceProvider.
        private void ReadKey(string filePath)
        {
            StreamReader sr = new StreamReader(filePath);
            string keyValue = sr.ReadLine();
            string ivValue = sr.ReadLine();
            des.Key = HexToByte(keyValue);
            des.IV = HexToByte(ivValue);
        


        // Converts a byte array to a hexadecimal string.
        private string ByteToHex(byte[] byteArray)
        {
            string outString = "";

            foreach (Byte b in byteArray)
                outString += b.ToString("X2");

            return outString;
        

        // Converts a hexadecimal string to a byte array.
        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;
        

    



The following example shows how to use the previous custom ProtectedConfigurationProvider.

Visual Basic
Imports System
Imports System.Xml
Imports System.Security.Cryptography
Imports System.IO
Imports System.Text
Imports System.Configuration.Provider
Imports System.Collections.Specialized
Imports System.Configuration


' Show how to use the ProtectedConfigurationProvider
' to create a custom protected configuration
' provider.

Public Class TripleDESProtectedConfigurationProvider
   Inherits ProtectedConfigurationProvider
   
    Private des _
    As New TripleDESCryptoServiceProvider()
   
   Private pKeyFilePath As String
   Private pName As String
   
   ' Gets the path of the file
   ' containing the key used to
   ' encrypt/decrypt.
   
   Public ReadOnly Property KeyFilePath() As String
      Get
         Return pKeyFilePath
      End Get
   End Property 
   
   ' Gets the provider name.
   
   Public Overrides ReadOnly Property Name() As String
      Get
         Return pName
      End Get
   End Property
    
   
   ' Performs provider initialization.
    Public Overrides Sub Initialize( _
    ByVal name As String, _
    ByVal config As NameValueCollection)
        pName = name
        pKeyFilePath = config("keyContainerName")
        ReadKey(KeyFilePath)
    End Sub 'Initialize
   
   
   ' Performs encryption.
    Public Overrides Function Encrypt( _
    ByVal node As XmlNode) As XmlNode
        Dim encryptedData As String = _
        EncryptString(node.OuterXml)

        Dim xmlDoc As New XmlDocument()
        xmlDoc.PreserveWhitespace = True
        xmlDoc.LoadXml( _
        ("<EncryptedData>" + encryptedData + _
        "</EncryptedData>"))

        Return xmlDoc.DocumentElement
    End Function 'Encrypt

   ' Performs decryption.
    Public Overrides Function Decrypt( _
    ByVal encryptedNode As XmlNode) As XmlNode
        Dim decryptedData As String = _
        DecryptString(encryptedNode.InnerText)

        Dim xmlDoc As New XmlDocument()
        xmlDoc.PreserveWhitespace = True
        xmlDoc.LoadXml(decryptedData)

        Return xmlDoc.DocumentElement
    End Function 'Decrypt

   
   
   ' Encrypts a configuration section and returns 
   ' the encrypted XML as a string.
    Private Function EncryptString( _
    ByVal encryptValue As String) As String
        Dim valBytes As Byte() = _
        Encoding.Unicode.GetBytes(encryptValue)

        Dim transform As ICryptoTransform = _
        des.CreateEncryptor()

        Dim ms As New MemoryStream()
        Dim cs As New CryptoStream(ms, _
        transform, CryptoStreamMode.Write)
        cs.Write(valBytes, 0, valBytes.Length)
        cs.FlushFinalBlock()
        Dim returnBytes As Byte() = ms.ToArray()
        cs.Close()

        Return Convert.ToBase64String(returnBytes)
    End Function 'EncryptString
   
   
   
   ' Decrypts an encrypted configuration section and 
   ' returns the unencrypted XML as a string.
    Private Function DecryptString( _
    ByVal encryptedValue As String) As String
        Dim valBytes As Byte() = _
        Convert.FromBase64String(encryptedValue)

        Dim transform As ICryptoTransform = _
        des.CreateDecryptor()

        Dim ms As New MemoryStream()
        Dim cs As New CryptoStream(ms, _
        transform, CryptoStreamMode.Write)
        cs.Write(valBytes, 0, valBytes.Length)
        cs.FlushFinalBlock()
        Dim returnBytes As Byte() = ms.ToArray()
        cs.Close()

        Return Encoding.Unicode.GetString(returnBytes)
    End Function 'DecryptString
   
   
   ' Generates a new TripleDES key and vector and 
   ' writes them to the supplied file path.
   Public Sub CreateKey(filePath As String)
      des.GenerateKey()
      des.GenerateIV()
      
      Dim sw As New StreamWriter(filePath, False)
      sw.WriteLine(ByteToHex(des.Key))
      sw.WriteLine(ByteToHex(des.IV))
      sw.Close()
   End Sub 'CreateKey
   
   
   
   ' Reads in the TripleDES key and vector from 
   ' the supplied file path and sets the Key 
   ' and IV properties of the 
   ' TripleDESCryptoServiceProvider.
   Private Sub ReadKey(filePath As String)
      Dim sr As New StreamReader(filePath)
      Dim keyValue As String = sr.ReadLine()
      Dim ivValue As String = sr.ReadLine()
      des.Key = HexToByte(keyValue)
      des.IV = HexToByte(ivValue)
   End Sub 'ReadKey
   
   
   
   ' Converts a byte array to a hexadecimal string.
    Private Function ByteToHex( _
    ByVal byteArray() As Byte) As String
        Dim outString As String = ""

        Dim b As [Byte]
        For Each b In byteArray
            outString += b.ToString("X2")
        Next b
        Return outString
    End Function 'ByteToHex
   
   
   ' Converts a hexadecimal string to a byte array.
   Private Function HexToByte(hexString As String) As Byte()
      Dim returnBytes(hexString.Length / 2) As Byte
      Dim i As Integer
      For i = 0 To returnBytes.Length - 1
            returnBytes(i) = _
            Convert.ToByte(hexString.Substring(i * 2, 2), 16)
      Next i
      Return returnBytes
   End Function 'HexToByte
End Class 'TripleDESProtectedConfigurationProvider 


C#
using System;
using System.Xml;
using System.Security.Cryptography;
using System.IO;
using System.Text;
using System.Configuration.Provider;
using System.Collections.Specialized;
using System.Configuration;

namespace Samples.AspNet.Configuration
{
    // Show how to use the ProtectedConfigurationProvider
    // to create a custom protected configuration
    // provider.
    public class TripleDESProtectedConfigurationProvider :
        ProtectedConfigurationProvider
    {

        private TripleDESCryptoServiceProvider des =
            new TripleDESCryptoServiceProvider();

        private string pKeyFilePath;
        private string pName;

        // Gets the path of the file
        // containing the key used to
        // encrypt/decrypt.
        public string KeyFilePath
        {
            get { return pKeyFilePath; 
        


        // Gets the provider name.
        public override string Name
        {
            get { return pName; 
        


        // Performs provider initialization.
        public override void Initialize(string name,
            NameValueCollection config)
        {
            pName = name;
            pKeyFilePath = config["keyContainerName"];
            ReadKey(KeyFilePath);
        


        // Performs encryption.
        public override XmlNode Encrypt(XmlNode node)
        {
            string encryptedData = EncryptString(node.OuterXml);

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.PreserveWhitespace = true;
            xmlDoc.LoadXml("<EncryptedData>" +
                encryptedData + "</EncryptedData>");

            return xmlDoc.DocumentElement;
        

        // Performs decryption.
        public override XmlNode Decrypt(XmlNode encryptedNode)
        {
            string decryptedData =
                DecryptString(encryptedNode.InnerText);

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.PreserveWhitespace = true;
            xmlDoc.LoadXml(decryptedData);

            return xmlDoc.DocumentElement;
        

        // Encrypts a configuration section and returns 
        // the encrypted XML as a string.
        private string EncryptString(string encryptValue)
        {
            byte[] valBytes =
                Encoding.Unicode.GetBytes(encryptValue);

            ICryptoTransform transform = des.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);
        


        // Decrypts an encrypted configuration section and 
        // returns the unencrypted XML as a string.
        private string DecryptString(string encryptedValue)
        {
            byte[] valBytes =
                Convert.FromBase64String(encryptedValue);

            ICryptoTransform transform = des.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);
        

        // Generates a new TripleDES key and vector and 
        // writes them to the supplied file path.
        public void CreateKey(string filePath)
        {
            des.GenerateKey();
            des.GenerateIV();

            StreamWriter sw = new StreamWriter(filePath, false);
            sw.WriteLine(ByteToHex(des.Key));
            sw.WriteLine(ByteToHex(des.IV));
            sw.Close();
        


        // Reads in the TripleDES key and vector from 
        // the supplied file path and sets the Key 
        // and IV properties of the 
        // TripleDESCryptoServiceProvider.
        private void ReadKey(string filePath)
        {
            StreamReader sr = new StreamReader(filePath);
            string keyValue = sr.ReadLine();
            string ivValue = sr.ReadLine();
            des.Key = HexToByte(keyValue);
            des.IV = HexToByte(ivValue);
        


        // Converts a byte array to a hexadecimal string.
        private string ByteToHex(byte[] byteArray)
        {
            string outString = "";

            foreach (Byte b in byteArray)
                outString += b.ToString("X2");

            return outString;
        

        // Converts a hexadecimal string to a byte array.
        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;
        

    



The following is an excerpt of the configuration file used by the above examples.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <configProtectedData >
    <providers>
      <clear />
      <add keyContainerName="pcKey.txt" 
        name="TripleDESProtectedConfigurationProvider"
type="Samples.Aspnet.Configuration.TripleDESProtectedConfigurationProvider, protectedconfigurationproviderlib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=79e01ae0f5cfc66f, processorArchitecture=MSIL" />
    </providers>

     

  </configProtectedData >

  <connectionStrings>
    <add name="NorthwindConnectionString" 
      connectionString="Data Source=webnetue2;Initial Catalog=Northwind;User ID=aspnet_test;Password=test"
providerName="System.Data.SqlClient" />
  </connectionStrings>

</configuration>
Inheritance Hierarchy

System.Object
   System.Configuration.Provider.ProviderBase
    System.Configuration.ProtectedConfigurationProvider
       System.Configuration.DpapiProtectedConfigurationProvider
       System.Configuration.RsaProtectedConfigurationProvider
Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Platforms

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

Version Information

.NET Framework

Supported in: 2.0
See Also