RsaProtectedConfigurationProvider Класс

Определение

Предоставляет экземпляр ProtectedConfigurationProvider, использующий шифрование RSA для зашифровки и дешифровки данных конфигурации.

public ref class RsaProtectedConfigurationProvider sealed : System::Configuration::ProtectedConfigurationProvider
public sealed class RsaProtectedConfigurationProvider : System.Configuration.ProtectedConfigurationProvider
type RsaProtectedConfigurationProvider = class
    inherit ProtectedConfigurationProvider
Public NotInheritable Class RsaProtectedConfigurationProvider
Inherits ProtectedConfigurationProvider
Наследование
RsaProtectedConfigurationProvider

Примеры

В следующем примере показано, как использовать стандарт RsaProtectedConfigurationProvider для защиты или отмены защиты раздела конфигурации.

using System;
using System.Configuration;

public class UsingRsaProtectedConfigurationProvider
{

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

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

        // Define the Rsa provider name.
        string provider =
            "RsaProtectedConfigurationProvider";

        // 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 protect or unprotect");
            return;
        }

        selection = args[0].ToLower();

        switch (selection)
        {
            case "protect":
                ProtectConfiguration();
                break;

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

        Console.Read();
    }
}

Imports System.Configuration


Public Class UsingRsaProtectedConfigurationProvider
   
   
   ' 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 Rsa provider name.
        Dim provider As String = _
        "RsaProtectedConfigurationProvider"
      
      ' 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 protect or unprotect")
            Return
        End If

        selection = args(0).ToLower()

        Select Case selection
            Case "protect"
                ProtectConfiguration()

            Case "unprotect"
                UnProtectConfiguration()

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

        Console.Read()
    End Sub

End Class

В следующем примере показан фрагмент из файла конфигурации после шифрования.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings configProtectionProvider="RsaProtectedConfigurationProvider">
    <EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element"
        xmlns="http://www.w3.org/2001/04/xmlenc#">
      <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
      <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
        <EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#">
          <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
          <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
            <KeyName>Rsa Key</KeyName>
          </KeyInfo>
          <CipherData>
            <CipherValue>B702tRDVHJjC3CYXt7I0ucCDjdht/Vyk/DdUhwQyt7vepSD85dwCP8ox9Y1BUdjajFeTFfFBsGypbli5HPGRYamQdrVkPo07bBBXNT5H02qxREguGUU4iDtV1Xp8BLVZjQMV4ZgP6Wbctw2xRvPC7GvKHLI4fUN/Je5LmutsijA=</CipherValue>
          </CipherData>
        </EncryptedKey>
      </KeyInfo>
      <CipherData>
        <CipherValue>ME+XJA2TAj3QN3yT4pJq3sRArC0i7Cz3Da71BkaRe9QNfuVuUjcv0jeGUN4wDdOAZ7LPq6UpVrpirY3kQcALDvPJ5nKxk++Mw75rjtIO8eh2goTY9rCK6zanfzaDshFy7IqItpvs/y2kmij25nM3ury6uO0hCf0UbEL1mbT2jXDqvcrHZUobO1Ef6bygBZ/8HpU+VfF9CTCob/BBE9zUkK37EQhcduwsnzBvDblYbF/Rd+F4lxAkZnecGLfCZjOzJB4xH1a0vvWtPR7zNwL/7I0uHzQjyMdWrkBnotMjoR70R7NELBotCogWO0MBimncKigdR3dTTdrCd72a7UJ4LMlEQaZXGIJp4PIg6qVDHII=</CipherValue>
      </CipherData>
    </EncryptedData>
  </connectionStrings>
</configuration>

Комментарии

Класс RsaProtectedConfigurationProvider предоставляет способ шифрования конфиденциальной информации, хранящейся в файле конфигурации, что помогает защитить ее от несанкционированного доступа. Встроенный RsaProtectedConfigurationProvider экземпляр используется путем объявления поставщика и внесения соответствующих параметров в файл конфигурации вместо создания экземпляра этого класса, как показано в разделе Примеры.

Объект RsaProtectedConfigurationProvider использует функции шифрования, предоставляемые классом RSA , для шифрования и расшифровки разделов конфигурации.

Примечание

Прежде чем ASP.NET сможет расшифровать зашифрованные сведения в файле конфигурации, удостоверение приложения ASP.NET должно иметь доступ на чтение к ключу шифрования, используемому для шифрования и расшифровки данных конфигурации. Дополнительные сведения см. в разделе Пошаговое руководство. Шифрование сведений о конфигурации с помощью защищенной конфигурации.

Примечание

В .NET Core и .NET 5+ RsaProtectedConfigurationProvider тип не поддерживается. Все API вызывают исключение PlatformNotSupportedException во время выполнения.

Конструкторы

RsaProtectedConfigurationProvider()

Инициализирует новый экземпляр класса RsaProtectedConfigurationProvider.

Свойства

CspProviderName

Возвращает имя API шифрования Windows (API шифрования) поставщика служб шифрования (CSP).

Description

Возвращает краткое, понятное описание, подходящее для отображения в инструментах администрирования или других пользовательских интерфейсах (UI).

(Унаследовано от ProviderBase)
KeyContainerName

Возвращает имя контейнера ключа.

Name

Возвращает понятное имя, используемое для ссылки на поставщика во время конфигурирования.

(Унаследовано от ProviderBase)
RsaPublicKey

Возвращает открытый ключ, используемый поставщиком.

UseFIPS

Возвращает значение, указывающее, использует ли поставщик FIPS.

UseMachineContainer

Возвращает значение, указывающее на то, использует ли объект RsaProtectedConfigurationProvider контейнер ключа машины.

UseOAEP

Возвращает значение, которое указывает на то, использует ли поставщик данные обмена ключа Optimal Asymmetric Encryption Padding (OAEP).

Методы

AddKey(Int32, Boolean)

Добавляет ключ к контейнеру ключа RSA.

Decrypt(XmlNode)

Расшифровывает переданный узел XML.

DeleteKey()

Удаляет ключ из контейнера ключа RSA.

Encrypt(XmlNode)

Зашифровывает переданный в него узел XML.

Equals(Object)

Определяет, равен ли указанный объект текущему объекту.

(Унаследовано от Object)
ExportKey(String, Boolean)

Экспортирует ключ RSA из контейнера ключа.

GetHashCode()

Служит хэш-функцией по умолчанию.

(Унаследовано от Object)
GetType()

Возвращает объект Type для текущего экземпляра.

(Унаследовано от Object)
ImportKey(String, Boolean)

Импортирует ключ RSA в ключ контейнера.

Initialize(String, NameValueCollection)

Выполняет инициализацию поставщика параметров по умолчанию.

Initialize(String, NameValueCollection)

Инициализирует построитель конфигураций.

(Унаследовано от ProviderBase)
MemberwiseClone()

Создает неполную копию текущего объекта Object.

(Унаследовано от Object)
ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)

Применяется к

См. также раздел