Dieser Artikel wurde manuell übersetzt. Bewegen Sie den Mauszeiger über die Sätze im Artikel, um den Originaltext anzuzeigen.
Übersetzung
Original
Dieser Artikel wurde noch nicht bewertet - Dieses Thema bewerten.

ProtectedConfigurationProvider-Klasse

Dies ist die Basisklasse zum Erstellen von Anbietern für das Verschlüsseln und Entschlüsseln von Daten der geschützten Konfiguration.

Namespace:  System.Configuration
Assembly:  System.Configuration (in System.Configuration.dll)
public abstract class ProtectedConfigurationProvider : ProviderBase

Der ProtectedConfigurationProvider-Typ macht die folgenden Member verfügbar.

  Name Beschreibung
Geschützte Methode ProtectedConfigurationProvider Initialisiert eine neue Instanz der ProtectedConfigurationProvider-Klasse mit Standardeinstellungen.
Zum Seitenanfang
  Name Beschreibung
Öffentliche Eigenschaft Description Ruft eine kurze, benutzerfreundliche Beschreibung ab, die für die Anzeige in Verwaltungstools oder anderen Benutzeroberflächen geeignet ist. (Von ProviderBase geerbt.)
Öffentliche Eigenschaft Name Ruft den Anzeigennamen ab, der verwendet wird, um während der Konfiguration auf den Anbieter zu verweisen. (Von ProviderBase geerbt.)
Zum Seitenanfang
  Name Beschreibung
Öffentliche Methode Decrypt Entschlüsselt das übergebene XmlNode-Objekt aus einer Konfigurationsdatei.
Öffentliche Methode Encrypt Verschlüsselt das übergebene XmlNode-Objekt aus einer Konfigurationsdatei.
Öffentliche Methode Equals(Object) Bestimmt, ob das angegebene Object und das aktuelle Object gleich sind. (Von Object geerbt.)
Geschützte Methode Finalize Gibt einem Objekt Gelegenheit zu dem Versuch, Ressourcen freizugeben und andere Bereinigungen durchzuführen, bevor es von der automatische Speicherbereinigung freigegeben wird. (Von Object geerbt.)
Öffentliche Methode GetHashCode Fungiert als Hashfunktion für einen bestimmten Typ. (Von Object geerbt.)
Öffentliche Methode GetType Ruft den Type der aktuellen Instanz ab. (Von Object geerbt.)
Öffentliche Methode Initialize Initialisiert den Anbieter. (Von ProviderBase geerbt.)
Geschützte Methode MemberwiseClone Erstellt eine flache Kopie des aktuellen Object. (Von Object geerbt.)
Öffentliche Methode ToString Gibt eine Zeichenfolge zurück, die das aktuelle Objekt darstellt. (Von Object geerbt.)
Zum Seitenanfang

Sie können Abschnitte einer Konfigurationsdatei verschlüsseln, um vertrauliche Informationen zu schützen, die von der Anwendung verwendet werden. Dadurch wird die Sicherheit verbessert, weil ein unbefugter Zugriff auch dann erschwert wird, wenn ein Angreifer Zugriff auf Ihre Konfigurationsdatei erhält.

.NET Framework enthält zwei geschützte Konfigurationsanbieter, die zum Verschlüsseln von Abschnitten in einer Konfigurationsdatei verwendet werden können. Die RsaProtectedConfigurationProvider-Klasse zum Verschlüsseln von Konfigurationsabschnitten verwendet den RSACryptoServiceProvider. Die DpapiProtectedConfigurationProvider-Klasse verwendet zum Verschlüsseln von Konfigurationsabschnitten die Windows-Data Protection-API (DPAPI).

Möglicherweise ist es für Sie erforderlich, vertrauliche Informationen mithilfe eines anderen Algorithmus als den RSA- oder DPAPI-Anbietern zu verschlüsseln. In diesem Fall können Sie ihren eigenen benutzerdefinierten Anbieter der geschützten Konfiguration erstellen. ProtectedConfigurationProvider ist eine abstrakte Basisklasse, die Sie erben müssen, um Ihren eigenen Anbieter der geschützten Konfiguration zu erstellen.

Unabhängig davon, ob Sie einen Standardanbieter oder einen benutzerdefinierten Anbieter verwenden, müssen Sie sicherstellen, dass er mit dem add-Element im Abschnitt providers des Konfigurationsabschnitts configProtectedData konfiguriert wird. (Siehe nächstes Beispiel.)

Ausführliche Informationen finden Sie unter Implementieren eines geschützten Konfigurationsanbieters.

Hinweis Hinweis

Wenn ASP.NET auf verschlüsselte Konfigurationsdaten trifft, führt es unter transparenter Verwendung des konfigurierten Anbieters eine Entschlüsselung durch. Sie müssen keine weiteren Schritte ausführen. Sie müssen nur sicherstellen, dass Sie den erforderlichen Anbieter konfigurieren.

Im folgenden Beispiel wird veranschaulicht, wie ein benutzerdefinierter ProtectedConfigurationProvider implementiert wird.

Um diesen Anbieter konfigurieren zu können, wie im nächsten Konfigurationsauszug gezeigt, müssen Sie ihn im globalen Assemblycache (GAC) installieren. Weitere Informationen finden Sie unter Implementieren eines geschützten Konfigurationsanbieters.


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;
        }

    }

}


Das folgende Beispiel veranschaulicht, wie der vorherige benutzerdefinierte ProtectedConfigurationProvider verwendet wird.


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();

        }


    }

}


Es folgt ein Auszug aus der Konfigurationsdatei, die von den oben genannten Beispielen verwendet wird.

<?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

Unterstützt in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Unterstützt in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 oder höher, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core wird nicht unterstützt), Windows Server 2008 R2 (Server Core wird mit SP1 oder höher unterstützt), Windows Server 2003 SP2

.NET Framework unterstützt nicht alle Versionen sämtlicher Plattformen. Eine Liste der unterstützten Versionen finden Sie unter Systemanforderungen für .NET Framework.
Alle öffentlichen static (Shared in Visual Basic)-Member dieses Typs sind threadsicher. Bei Instanzmembern ist die Threadsicherheit nicht gewährleistet.
Fanden Sie dies hilfreich?
(1500 verbleibende Zeichen)
Community-Inhalt Hinzufügen
Anmerkungen FAQ