RsaProtectedConfigurationProvider Clase

Definición

Proporciona una instancia de ProtectedConfigurationProvider que usa el cifrado RSA para cifrar y descifrar los datos de configuración.

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
Herencia
RsaProtectedConfigurationProvider

Ejemplos

En el ejemplo siguiente se muestra cómo usar el estándar RsaProtectedConfigurationProvider para proteger o desproteger una sección de configuración.

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

En el ejemplo siguiente se muestra un extracto de un archivo de configuración después del cifrado.

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

Comentarios

La RsaProtectedConfigurationProvider clase proporciona una manera de cifrar la información confidencial almacenada en un archivo de configuración, lo que ayuda a protegerla frente al acceso no autorizado. Para usar la instancia integrada RsaProtectedConfigurationProvider , declare el proveedor y realice las opciones adecuadas en el archivo de configuración en lugar de crear una instancia de esta clase, como se muestra en la sección Ejemplos.

El RsaProtectedConfigurationProvider objeto usa las funciones de criptografía proporcionadas por RSA la clase para cifrar y descifrar secciones de configuración.

Nota:

Antes de que ASP.NET pueda descifrar la información cifrada en el archivo de configuración, la identidad de la aplicación de ASP.NET debe tener acceso de lectura a la clave de cifrado utilizada para cifrar y descifrar los datos de configuración. Para obtener más información, vea Tutorial: Cifrado de información de configuración mediante la configuración protegida.

Nota:

En .NET Core y .NET 5+, no se admite el RsaProtectedConfigurationProvider tipo. Todas las API inician una PlatformNotSupportedException en tiempo de ejecución.

Constructores

RsaProtectedConfigurationProvider()

Inicializa una nueva instancia de la clase RsaProtectedConfigurationProvider.

Propiedades

CspProviderName

Obtiene el nombre del proveedor de servicios criptográficos (CSP) de la API de Windows Cryptography (CryptoAPI).

Description

Obtiene una descripción breve y fácil de comprender apropiada para mostrarla en las herramientas administrativas u otras interfaces de usuario.

(Heredado de ProviderBase)
KeyContainerName

Obtiene el nombre del contenedor de claves.

Name

Obtiene el nombre descriptivo utilizado para hacer referencia al proveedor durante la configuración.

(Heredado de ProviderBase)
RsaPublicKey

Obtiene la clave pública que usa el proveedor.

UseFIPS

Obtiene un valor que indica si el proveedor usa FIPS.

UseMachineContainer

Obtiene un valor que indica si el objeto RsaProtectedConfigurationProvider está usando el contenedor de claves del equipo.

UseOAEP

Obtiene un valor que indica si el proveedor está usando los datos de intercambio de claves de OAEP (Optimal Asymmetric Encryption Padding, Relleno óptimo de cifrado asimétrico).

Métodos

AddKey(Int32, Boolean)

Agrega una clave al contenedor de claves RSA.

Decrypt(XmlNode)

Descifra el nodo de XML que se le pasó.

DeleteKey()

Quita una clave del contenedor de claves RSA.

Encrypt(XmlNode)

Cifra el nodo de XML que se le pasó.

Equals(Object)

Determina si el objeto especificado es igual que el objeto actual.

(Heredado de Object)
ExportKey(String, Boolean)

Exporta una clave RSA del contenedor de claves.

GetHashCode()

Sirve como la función hash predeterminada.

(Heredado de Object)
GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
ImportKey(String, Boolean)

Importa una clave RSA al contenedor de claves.

Initialize(String, NameValueCollection)

Inicializa el proveedor con la configuración predeterminada.

Initialize(String, NameValueCollection)

Inicializa el generador de configuración.

(Heredado de ProviderBase)
MemberwiseClone()

Crea una copia superficial del Object actual.

(Heredado de Object)
ToString()

Devuelve una cadena que representa el objeto actual.

(Heredado de Object)

Se aplica a

Consulte también