RsaProtectedConfigurationProvider Classe
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Fornece uma ProtectedConfigurationProvider instância que utiliza encriptação RSA para encriptar e desencriptar dados de configuração.
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
- Herança
Exemplos
O exemplo seguinte mostra como usar a norma RsaProtectedConfigurationProvider para proteger ou desproteger uma secção de configuração.
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
O exemplo seguinte mostra um excerto de um ficheiro de configuração após a encriptação.
<?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>
Observações
A RsaProtectedConfigurationProvider classe dá-te uma forma de encriptar informação sensível armazenada num ficheiro de configuração, o que ajuda a protegê-la de acessos não autorizados. Utiliza-se a instância incorporada RsaProtectedConfigurationProvider declarando o fornecedor e fazendo as definições apropriadas no ficheiro de configuração em vez de criar uma instância desta classe, como mostrado na secção Exemplos.
O RsaProtectedConfigurationProvider objeto utiliza as funções de criptografia fornecidas pela RSA classe para encriptar e desencriptar secções de configuração.
Note
Antes de o ASP.NET poder desencriptar informações encriptadas no seu ficheiro de configuração, a identidade da sua aplicação ASP.NET deve ter acesso de leitura à chave de encriptação usada para encriptar e desencriptar os dados de configuração. Para mais informações, consulte Guia: Encriptação de Informação de Configuração Usando Configuração Protegida.
Note
No .NET Core e no .NET 5+, o tipo RsaProtectedConfigurationProvider não é suportado. Todas as APIs apresentam um PlatformNotSupportedException em tempo de execução.
Construtores
| Name | Description |
|---|---|
| RsaProtectedConfigurationProvider() |
Inicializa uma nova instância da RsaProtectedConfigurationProvider classe. |
Propriedades
| Name | Description |
|---|---|
| CspProviderName |
Recebe o nome do fornecedor de serviços criptográficos (CSP) da API de criptografia do Windows (API criptográfica). |
| Description |
Recebe uma descrição breve e amigável, adequada para exibição em ferramentas administrativas ou outras interfaces de utilizador (UIs). (Herdado de ProviderBase) |
| KeyContainerName |
Obtém o nome do recipiente da chave. |
| Name |
Recebe o nome amigável usado para se referir ao fornecedor durante a configuração. (Herdado de ProviderBase) |
| RsaPublicKey |
Obtém a chave pública usada pelo fornecedor. |
| UseFIPS |
Recebe um valor que indica se o fornecedor utiliza FIPS. |
| UseMachineContainer |
Obtém um valor que indica se o RsaProtectedConfigurationProvider objeto está a usar o contentor de chaves da máquina. |
| UseOAEP |
Obtém um valor que indica se o fornecedor está a usar dados de troca de chaves Optimal Asymmetric Encryption Padding (OAEP). |
Métodos
| Name | Description |
|---|---|
| AddKey(Int32, Boolean) |
Adiciona uma chave ao contentor de chaves RSA. |
| Decrypt(XmlNode) |
Descifra o nó XML que lhe é passado. |
| DeleteKey() |
Remove uma chave do contentor de chaves RSA. |
| Encrypt(XmlNode) |
Encripta o nó XML que lhe foi passado. |
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual. (Herdado de Object) |
| ExportKey(String, Boolean) |
Exporta uma chave RSA do contentor de chaves. |
| GetHashCode() |
Serve como função de hash predefinida. (Herdado de Object) |
| GetType() |
Obtém o Type da instância atual. (Herdado de Object) |
| ImportKey(String, Boolean) |
Importa uma chave RSA para o contentor de chaves. |
| Initialize(String, NameValueCollection) |
Inicializa o fornecedor com as definições predefinidas. |
| Initialize(String, NameValueCollection) |
Inicializa o construtor de configuração. (Herdado de ProviderBase) |
| MemberwiseClone() |
Cria uma cópia superficial do atual Object. (Herdado de Object) |
| ToString() |
Devolve uma cadeia que representa o objeto atual. (Herdado de Object) |