다음을 통해 공유


ProtectedConfigurationProvider 클래스

정의

보호된 구성 데이터를 암호화하고 해독하기 위한 공급자를 만드는 기본 클래스입니다.

public ref class ProtectedConfigurationProvider abstract : System::Configuration::Provider::ProviderBase
public abstract class ProtectedConfigurationProvider : System.Configuration.Provider.ProviderBase
type ProtectedConfigurationProvider = class
    inherit ProviderBase
Public MustInherit Class ProtectedConfigurationProvider
Inherits ProviderBase
상속
ProtectedConfigurationProvider
파생

예제

다음 예제에서는 사용자 지정 ProtectedConfigurationProvider를 구현하는 방법을 보여줍니다.

다음 구성 발췌에 표시된 것처럼 이 공급자를 구성하려면 GAC(전역 어셈블리 캐시)에 설치해야 합니다. 자세한 내용은 보호된 구성 공급자 구현 을 참조하세요.

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
{
    // Shows how 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
        // encryption or decryption.
        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;
        }
    }
}
Imports System.Xml
Imports System.Security.Cryptography
Imports System.IO
Imports System.Text
Imports System.Configuration.Provider
Imports System.Collections.Specialized
Imports System.Configuration


' Shows how to create a custom protected configuration
' provider.
Namespace Samples.AspNet

    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


        ' 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(ByVal 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



        ' 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(ByVal 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



        ' 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(ByVal 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

End Namespace

다음 예제에서는 이전 사용자 지정 ProtectedConfigurationProvider를 사용하는 방법을 보여 있습니다.

using System;
using System.Configuration;
using Samples.AspNet.Configuration;

namespace Samples.AspNet.Configuration
{

    // Show how to use a custom protected configuration
    // provider.
    public class TestingProtectedConfigurationProvider
    {

        // Protect the connectionStrings section.
        private static void ProtectConfiguration()
        {

            // Get the application configuration file.
            System.Configuration.Configuration config =
                    ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None);

            // Define the provider name.
            string provider =
                "TripleDESProtectedConfigurationProvider";

            // Get the section to protect.
            ConfigurationSection connStrings =
                config.ConnectionStrings;

            if (connStrings != null)
            {
                if (!connStrings.SectionInformation.IsProtected)
                {
                    if (!connStrings.ElementInformation.IsLocked)
                    {
                        // Protect the section.
                        connStrings.SectionInformation.ProtectSection(provider);

                        connStrings.SectionInformation.ForceSave = true;
                        config.Save(ConfigurationSaveMode.Full);

                        Console.WriteLine("Section {0} is now protected by {1}",
                            connStrings.SectionInformation.Name,
                            connStrings.SectionInformation.ProtectionProvider.Name);
                    }
                    else
                        Console.WriteLine(
                             "Can't protect, section {0} is locked",
                             connStrings.SectionInformation.Name);
                }
                else
                    Console.WriteLine(
                        "Section {0} is already protected by {1}",
                        connStrings.SectionInformation.Name,
                        connStrings.SectionInformation.ProtectionProvider.Name);
            }
            else
                Console.WriteLine("Can't get the section {0}",
                    connStrings.SectionInformation.Name);
        }

        // Unprotect the connectionStrings section.
        private static void UnProtectConfiguration()
        {

            // Get the application configuration file.
            System.Configuration.Configuration config =
                    ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None);

            // Get the section to unprotect.
            ConfigurationSection connStrings =
                config.ConnectionStrings;

            if (connStrings != null)
            {
                if (connStrings.SectionInformation.IsProtected)
                {
                    if (!connStrings.ElementInformation.IsLocked)
                    {
                        // Unprotect the section.
                        connStrings.SectionInformation.UnprotectSection();

                        connStrings.SectionInformation.ForceSave = true;
                        config.Save(ConfigurationSaveMode.Full);

                        Console.WriteLine("Section {0} is now unprotected.",
                            connStrings.SectionInformation.Name);
                    }
                    else
                        Console.WriteLine(
                             "Can't unprotect, section {0} is locked",
                             connStrings.SectionInformation.Name);
                }
                else
                    Console.WriteLine(
                        "Section {0} is already unprotected.",
                        connStrings.SectionInformation.Name);
            }
            else
                Console.WriteLine("Can't get the section {0}",
                    connStrings.SectionInformation.Name);
        }

        public static void Main(string[] args)
        {

            string selection = string.Empty;

            if (args.Length == 0)
            {
                Console.WriteLine(
                    "Select createkey, protect or unprotect");
                return;
            }

            selection = args[0].ToLower();

            switch (selection)
            {

                // Create the key to use during 
                // encryption/decryption.
                case "createkey":
                    string keyContainer = 
                        "pcKey.txt";

                    // Instantiate the custom provider.
                    TripleDESProtectedConfigurationProvider 
                        provider =
                        new TripleDESProtectedConfigurationProvider();

                    // Create the encryption/decryption key.
                    provider.CreateKey(keyContainer);

                    Console.WriteLine(
                        "New TripleDES key created in {0}",
                        keyContainer);
                    break;

                case "protect":
                    ProtectConfiguration();
                    break;

                case "unprotect":
                    UnProtectConfiguration();
                    break;

                default:
                    Console.WriteLine("Unknown selection");
                    break;
            }

            Console.Read();
        }
    }
}
Imports System.Configuration

Namespace Samples.AspNet
    ' Show how to use a custom protected configuration
    ' provider.

    Public Class TestingProtectedConfigurationProvider


        ' Protect the connectionStrings section.
        Private Shared Sub ProtectConfiguration()

            ' Get the application configuration file.
            Dim config _
            As System.Configuration.Configuration = _
            ConfigurationManager.OpenExeConfiguration( _
            ConfigurationUserLevel.None)

            ' Define the provider name.
            Dim provider As String = _
            "TripleDESProtectedConfigurationProvider"

            ' Get the section to protect.
            Dim connStrings _
            As ConfigurationSection = config.ConnectionStrings

            If Not (connStrings Is Nothing) Then
                If Not connStrings.SectionInformation.IsProtected Then
                    If Not connStrings.ElementInformation.IsLocked Then
                        ' Protect the section.
                        connStrings.SectionInformation.ProtectSection( _
                        provider)

                        connStrings.SectionInformation.ForceSave = True
                        config.Save(ConfigurationSaveMode.Full)

                        Console.WriteLine( _
                        "Section {0} is now protected by {1}", _
                        connStrings.SectionInformation.Name, _
                        connStrings.SectionInformation.ProtectionProvider.Name)

                    Else
                        Console.WriteLine( _
                        "Can't protect, section {0} is locked", _
                        connStrings.SectionInformation.Name)
                    End If
                Else
                    Console.WriteLine( _
                    "Section {0} is already protected by {1}", _
                    connStrings.SectionInformation.Name, _
                    connStrings.SectionInformation.ProtectionProvider.Name)
                End If

            Else
                Console.WriteLine( _
                "Can't get the section {0}", _
                connStrings.SectionInformation.Name)
            End If
        End Sub


        ' Unprotect the connectionStrings section.
        Private Shared Sub UnProtectConfiguration()

            ' Get the application configuration file.
            Dim config _
            As System.Configuration.Configuration = _
            ConfigurationManager.OpenExeConfiguration( _
            ConfigurationUserLevel.None)

            ' Get the section to unprotect.
            Dim connStrings _
            As ConfigurationSection = config.ConnectionStrings

            If Not (connStrings Is Nothing) Then
                If connStrings.SectionInformation.IsProtected Then
                    If Not connStrings.ElementInformation.IsLocked Then
                        ' Unprotect the section.
                        connStrings.SectionInformation.UnprotectSection()

                        connStrings.SectionInformation.ForceSave = True
                        config.Save(ConfigurationSaveMode.Full)

                        Console.WriteLine( _
                        "Section {0} is now unprotected.", _
                        connStrings.SectionInformation.Name)

                    Else
                        Console.WriteLine( _
                        "Can't unprotect, section {0} is locked", _
                        connStrings.SectionInformation.Name)
                    End If
                Else
                    Console.WriteLine( _
                    "Section {0} is already unprotected.", _
                    connStrings.SectionInformation.Name)
                End If

            Else
                Console.WriteLine( _
                "Can't get the section {0}", _
                connStrings.SectionInformation.Name)
            End If
        End Sub



        Public Shared Sub Main(ByVal args() As String)

            Dim selection As String = String.Empty

            If args.Length = 0 Then
                Console.WriteLine( _
                "Select createkey, protect or unprotect")
                Return
            End If

            selection = args(0).ToLower()

            Select Case selection

                ' Create the key to use during 
                ' encryption/decryption.
                Case "createkey"
                    Dim keyContainer As String = "pcKey.txt"

                    ' Instantiate the custom provider.
                    Dim provider _
                    As New TripleDESProtectedConfigurationProvider()

                    ' Create the encryption/decryption key.
                    provider.CreateKey(keyContainer)

                    Console.WriteLine( _
                    "New TripleDES key created in {0}", _
                    keyContainer)

                Case "protect"
                    ProtectConfiguration()

                Case "unprotect"
                    UnProtectConfiguration()

                Case Else
                    Console.WriteLine("Unknown selection")
            End Select

            Console.Read()
        End Sub
    End Class
End Namespace

다음은 위의 예제에서 사용하는 구성 파일의 발췌입니다.

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

  <configProtectedData >
    <providers>
      <clear />
      <add keyContainerName="pcKey.txt"
        name="TripleDESProtectedConfigurationProvider"
type="Samples.Aspnet.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>

설명

애플리케이션에서 사용 하는 중요 한 정보를 보호 하는 구성 파일의 섹션을 암호화할 수 있습니다. 이렇게 하면 공격자가 구성 파일에 액세스하는 경우에도 무단 액세스가 어려워지므로 보안이 향상됩니다.

.NET Framework에는 구성 파일의 섹션을 암호화하는 데 사용할 수 있는 두 개의 보호된 구성 공급자가 포함되어 있습니다. 클래스는 RsaProtectedConfigurationProviderRSACryptoServiceProvider 사용하여 구성 섹션을 암호화합니다. 클래스는 DpapiProtectedConfigurationProvider Windows DPAPI(Data Protection API)를 사용하여 구성 섹션을 암호화합니다.

RSA 또는 DPAPI 공급자 이외의 알고리즘을 사용하여 중요한 정보를 암호화해야 할 수도 있습니다. 이 경우 고유한 사용자 지정 보호 구성 공급자를 빌드할 수 있습니다. 는 ProtectedConfigurationProvider 사용자 고유의 보호된 구성 공급자를 만들기 위해 상속해야 하는 추상 기본 클래스입니다.

표준 또는 사용자 지정 공급자를 사용하든 구성 섹션의 configProtectedData 요소 providersadd 구성되었는지 확인해야 합니다. (다음 예제를 참조하세요.)

자세한 내용은 보호된 구성 공급자 구현을 참조하세요.

참고

ASP.NET 암호화된 구성 데이터가 발견되면 구성된 공급자를 사용하여 암호 해독을 투명하게 수행합니다. 필요한 공급자를 구성하는 것 외에는 아무 작업도 필요하지 않습니다.

생성자

ProtectedConfigurationProvider()

기본 설정을 사용하여 ProtectedConfigurationProvider 클래스의 새 인스턴스를 초기화합니다.

속성

Description

관리 도구나 다른 UI(사용자 인터페이스)에 표시하기에 적합한 간단하고 이해하기 쉬운 설명을 가져옵니다.

(다음에서 상속됨 ProviderBase)
Name

구성 중 공급자를 참조하는 데 사용되는 이름을 가져옵니다.

(다음에서 상속됨 ProviderBase)

메서드

Decrypt(XmlNode)

구성 파일에서 전달된 XmlNode 개체를 해독합니다.

Encrypt(XmlNode)

구성 파일에서 전달된 XmlNode 개체를 암호화합니다.

Equals(Object)

지정된 개체가 현재 개체와 같은지 확인합니다.

(다음에서 상속됨 Object)
GetHashCode()

기본 해시 함수로 작동합니다.

(다음에서 상속됨 Object)
GetType()

현재 인스턴스의 Type을 가져옵니다.

(다음에서 상속됨 Object)
Initialize(String, NameValueCollection)

구성 작성기를 초기화합니다.

(다음에서 상속됨 ProviderBase)
MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
ToString()

현재 개체를 나타내는 문자열을 반환합니다.

(다음에서 상속됨 Object)

적용 대상

추가 정보