Protected Configuration Provider Implementation Example
The following code example shows how to implement a protected configuration provider. For details about how to build this provider and use it in an ASP.NET application, see How to: Build and Run the Protected Configuration Provider Example.
Example
Code
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
Namespace Samples.AspNet.ProtectedConfiguration
PublicClass TripleDESProtectedConfigurationProvider
Inherits ProtectedConfigurationProvider
Private des As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider()
Private pKeyFilePath AsStringPrivate pName AsStringPublicReadOnlyProperty KeyFilePath AsStringGetReturn pKeyFilePath
EndGetEndProperty
' ' ProviderBase.Name 'PublicOverridesReadOnlyProperty Name AsStringGetReturn pName
EndGetEndProperty
' ' ProviderBase.Initialize 'PublicOverridesSub Initialize(name AsString, config As NameValueCollection)
pName = name
pKeyFilePath = config("keyFilePath")
ReadKey(KeyFilePath)
EndSub
' ' ProtectedConfigurationProvider.Encrypt 'PublicOverridesFunction Encrypt(node As XmlNode ) As XmlNode
Dim encryptedData AsString = EncryptString(node.OuterXml)
Dim xmlDoc As XmlDocument = New XmlDocument()
xmlDoc.PreserveWhitespace = True
xmlDoc.LoadXml("<EncryptedData>" & encryptedData & "</EncryptedData>")
Return xmlDoc.DocumentElement
EndFunction
' ' ProtectedConfigurationProvider.Decrypt 'PublicOverridesFunction Decrypt(encryptedNode As XmlNode) As XmlNode
Dim decryptedData AsString = DecryptString(encryptedNode.InnerText)
Dim xmlDoc As XmlDocument = New XmlDocument()
xmlDoc.PreserveWhitespace = True
xmlDoc.LoadXml(decryptedData)
Return xmlDoc.DocumentElement
EndFunction
' ' EncryptString ' Encrypts a configuration section and returns the encrypted ' XML as a string. 'PrivateFunction EncryptString(encryptValue AsString) AsStringDim valBytes() AsByte = Encoding.Unicode.GetBytes(encryptValue)
Dim transform As ICryptoTransform = des.CreateEncryptor()
Dim ms As MemoryStream = New MemoryStream()
Dim cs As CryptoStream = New CryptoStream(ms, transform, CryptoStreamMode.Write)
cs.Write(valBytes, 0, valBytes.Length)
cs.FlushFinalBlock()
Dim returnBytes() AsByte = ms.ToArray()
cs.Close()
Return Convert.ToBase64String(returnBytes)
EndFunction
' ' DecryptString ' Decrypts an encrypted configuration section and returns the ' unencrypted XML as a string. 'PrivateFunction DecryptString(encryptedValue AsString) AsStringDim valBytes() AsByte = Convert.FromBase64String(encryptedValue)
Dim transform As ICryptoTransform = des.CreateDecryptor()
Dim ms As MemoryStream = New MemoryStream()
Dim cs As CryptoStream = New CryptoStream(ms, transform, CryptoStreamMode.Write)
cs.Write(valBytes, 0, valBytes.Length)
cs.FlushFinalBlock()
Dim returnBytes() AsByte = ms.ToArray()
cs.Close()
Return Encoding.Unicode.GetString(returnBytes)
EndFunction
' ' CreateKey ' Generates a New TripleDES key and vector and writes them ' to the supplied file path. 'PublicSub CreateKey(filePath AsString)
des.GenerateKey()
des.GenerateIV()
Dim sw As StreamWriter = New StreamWriter(filePath, false)
sw.WriteLine(ByteToHex(des.Key))
sw.WriteLine(ByteToHex(des.IV))
sw.Close()
EndSub
' ' ReadKey ' Reads in the TripleDES key and vector from the supplied ' file path and sets the Key and IV properties of the ' TripleDESCryptoServiceProvider. 'PrivateSub ReadKey(filePath AsString)
Dim sr As StreamReader = New StreamReader(filePath)
Dim keyValue AsString = sr.ReadLine()
Dim ivValue AsString = sr.ReadLine()
des.Key = HexToByte(keyValue)
des.IV = HexToByte(ivValue)
EndSub
' ' ByteToHex ' Converts a byte array to a hexadecimal string. 'PrivateFunction ByteToHex(byteArray AsByte()) AsStringDim outString AsString = ""ForEach b AsByteIn byteArray
outString &= b.ToString("X2")
NextReturn outString
EndFunction
' ' HexToByte ' Converts a hexadecimal string to a byte array. 'PrivateFunction HexToByte(hexString AsString) AsByte()
Dim returnBytes() AsByte = NewByte(CInt((hexString.Length / 2) - 1)) {}
For i AsInteger= 0 To returnBytes.Length - 1
returnBytes(i) = Convert.ToByte(hexString.Substring(i*2, 2), 16)
NextReturn returnBytes
EndFunctionEndClassEndNamespace
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.ProtectedConfiguration
{
publicclass TripleDESProtectedConfigurationProvider : ProtectedConfigurationProvider
{
private TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
privatestring pKeyFilePath;
privatestring pName;
publicstring KeyFilePath
{
get { return pKeyFilePath; }
}
//// ProviderBase.Name//publicoverridestring Name
{
get { return pName; }
}
//// ProviderBase.Initialize//publicoverridevoid Initialize(string name, NameValueCollection config)
{
pName = name;
pKeyFilePath = config["keyFilePath"];
ReadKey(KeyFilePath);
}
//// ProtectedConfigurationProvider.Encrypt//publicoverride XmlNode Encrypt(XmlNode node)
{
string encryptedData = EncryptString(node.OuterXml);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.PreserveWhitespace = true;
xmlDoc.LoadXml("<EncryptedData>" + encryptedData + "</EncryptedData>");
return xmlDoc.DocumentElement;
}
//// ProtectedConfigurationProvider.Decrypt//publicoverride XmlNode Decrypt(XmlNode encryptedNode)
{
string decryptedData = DecryptString(encryptedNode.InnerText);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.PreserveWhitespace = true;
xmlDoc.LoadXml(decryptedData);
return xmlDoc.DocumentElement;
}
//// EncryptString// Encrypts a configuration section and returns the encrypted// XML as a string.//privatestring 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);
}
//// DecryptString// Decrypts an encrypted configuration section and returns the// unencrypted XML as a string.//privatestring 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);
}
//// CreateKey// Generates a new TripleDES key and vector and writes them// to the supplied file path.//publicvoid 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();
}
//// ReadKey// Reads in the TripleDES key and vector from the supplied// file path and sets the Key and IV properties of the // TripleDESCryptoServiceProvider.//privatevoid ReadKey(string filePath)
{
StreamReader sr = new StreamReader(filePath);
string keyValue = sr.ReadLine();
string ivValue = sr.ReadLine();
des.Key = HexToByte(keyValue);
des.IV = HexToByte(ivValue);
}
//// ByteToHex// Converts a byte array to a hexadecimal string.//privatestring ByteToHex(byte[] byteArray)
{
string outString = "";
foreach (Byte b in byteArray)
outString += b.ToString("X2");
return outString;
}
//// HexToByte// Converts a hexadecimal string to a byte array.//privatebyte[] HexToByte(string hexString)
{
byte[] returnBytes = newbyte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i+)
returnBytes[i] = Convert.ToByte(hexString.Substring(i*2, 2), 16);
return returnBytes;
}
}
}
See Also
Tasks
How to: Build and Run the Protected Configuration Provider Example
Concepts
Implementing a Protected Configuration Provider
Other Resources
Encrypting Configuration Information Using Protected Configuration