DataProtector 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 a classe base para protetores de dados.
public ref class DataProtector abstract
public abstract class DataProtector
type DataProtector = class
Public MustInherit Class DataProtector
- Herança
-
DataProtector
- Derivado
Exemplos
O exemplo seguinte demonstra como criar um protetor de dados que utiliza uma classe de proteção com uma opção para entropia extra. Por defeito, a DataProtector classe antepõe o hash das propriedades de propósito aos dados a encriptar. Podes desligar essa funcionalidade e usar o propósito hashado como entropia extra ao chamar um protetor de dados com uma opção extra de entropia.
using System;
using System.Security.Permissions;
namespace System.Security.Cryptography
{
public sealed class MyDataProtector : DataProtector
{
public DataProtectionScope Scope { get; set; }
// This implementation gets the HashedPurpose from the base class and passes it as OptionalEntropy to ProtectedData.
// The default for DataProtector is to prepend the hash to the plain text, but because we are using the hash
// as OptionalEntropy there is no need to prepend it.
protected override bool PrependHashedPurposeToPlaintext
{
get
{
return false;
}
}
// To allow a service to hand out instances of a DataProtector we demand unrestricted DataProtectionPermission
// in the constructor, but Assert the permission when ProviderProtect is called. This is similar to FileStream
// where access is checked at time of creation, not time of use.
[SecuritySafeCritical]
[DataProtectionPermission(SecurityAction.Assert, ProtectData = true)]
protected override byte[] ProviderProtect(byte[] userData)
{
// Delegate to ProtectedData
return ProtectedData.Protect(userData, GetHashedPurpose(), Scope);
}
// To allow a service to hand out instances of a DataProtector we demand unrestricted DataProtectionPermission
// in the constructor, but Assert the permission when ProviderUnProtect is called. This is similar to FileStream
// where access is checked at time of creation, not time of use.
[SecuritySafeCritical]
[DataProtectionPermission(SecurityAction.Assert, UnprotectData = true)]
protected override byte[] ProviderUnprotect(byte[] encryptedData)
{
// Delegate to ProtectedData
return ProtectedData.Unprotect(encryptedData, GetHashedPurpose(), Scope);
}
public override bool IsReprotectRequired(byte[] encryptedData)
{
// For now, this cannot be determined, so always return true;
return true;
}
// Public constructor
// The Demand for DataProtectionPermission is in the constructor because we Assert this permission
// in the ProviderProtect/ProviderUnprotect methods.
[DataProtectionPermission(SecurityAction.Demand, Unrestricted = true)]
[SecuritySafeCritical]
public MyDataProtector(string appName, string primaryPurpose, params string[] specificPurpose)
: base(appName, primaryPurpose, specificPurpose)
{
}
}
}
Imports System.Security
Imports System.Security.Cryptography
Imports System.Security.Permissions
Public NotInheritable Class MyDataProtector
Inherits DataProtector
Public Property Scope() As DataProtectionScope
Get
Return Scope
End Get
Set(value As DataProtectionScope)
End Set
End Property ' This implementation gets the HashedPurpose from the base class and passes it as OptionalEntropy to ProtectedData.
' The default for DataProtector is to prepend the hash to the plain text, but because we are using the hash
' as OptionalEntropy there is no need to prepend it.
Protected Overrides ReadOnly Property PrependHashedPurposeToPlaintext() As Boolean
Get
Return False
End Get
End Property
' To allow a service to hand out instances of a DataProtector we demand unrestricted DataProtectionPermission
' in the constructor, but Assert the permission when ProviderProtect is called. This is similar to FileStream
' where access is checked at time of creation, not time of use.
<SecuritySafeCritical(), DataProtectionPermission(SecurityAction.Assert, ProtectData:=True)> _
Protected Overrides Function ProviderProtect(ByVal userData() As Byte) As Byte()
' Delegate to ProtectedData
Return ProtectedData.Protect(userData, GetHashedPurpose(), Scope)
End Function 'ProviderProtect
' To allow a service to hand out instances of a DataProtector we demand unrestricted DataProtectionPermission
' in the constructor, but Assert the permission when ProviderUnProtect is called. This is similar to FileStream
' where access is checked at time of creation, not time of use.
<SecuritySafeCritical(), DataProtectionPermission(SecurityAction.Assert, UnprotectData:=True)> _
Protected Overrides Function ProviderUnprotect(ByVal encryptedData() As Byte) As Byte()
' Delegate to ProtectedData
Return ProtectedData.Unprotect(encryptedData, GetHashedPurpose(), Scope)
End Function 'ProviderUnprotect
Public Overrides Function IsReprotectRequired(ByVal encryptedData() As Byte) As Boolean
' For now, this cannot be determined, so always return true;
Return True
End Function 'IsReprotectRequired
' Public constructor
' The Demand for DataProtectionPermission is in the constructor because we Assert this permission
' in the ProviderProtect/ProviderUnprotect methods.
<DataProtectionPermission(SecurityAction.Demand, Unrestricted:=True), SecuritySafeCritical()> _
Public Sub New(ByVal appName As String, ByVal primaryPurpose As String, ParamArray specificPurpose() As String)
MyBase.New(appName, primaryPurpose, specificPurpose)
End Sub
End Class
O exemplo seguinte demonstra um protetor de dados simples que utiliza a PrependHashedPurposeToPlaintext funcionalidade da DataProtector classe.
using System;
using System.Security.Permissions;
namespace System.Security.Cryptography
{
public sealed class MemoryProtector : DataProtector
{
public MemoryProtectionScope Scope { get; set; }
protected override bool PrependHashedPurposeToPlaintext
{
get
{
// Signal the DataProtector to prepend the hash of the purpose to the data.
return true;
}
}
// To allow a service to hand out instances of a DataProtector we demand unrestricted DataProtectionPermission
// in the constructor, but Assert the permission when ProviderProtect is called. This is similar to FileStream
// where access is checked at time of creation, not time of use.
[SecuritySafeCritical]
[DataProtectionPermission(SecurityAction.Assert, ProtectData = true)]
protected override byte[] ProviderProtect(byte[] userData)
{
// Delegate to ProtectedData
ProtectedMemory.Protect(userData, Scope);
return userData;
}
// To allow a service to hand out instances of a DataProtector we demand unrestricted DataProtectionPermission
// in the constructor, but Assert the permission when ProviderUnprotect is called.. This is similar to FileStream
// where access is checked at time of creation, not time of use.
[SecuritySafeCritical]
[DataProtectionPermission(SecurityAction.Assert, UnprotectData = true)]
protected override byte[] ProviderUnprotect(byte[] encryptedData)
{
ProtectedMemory.Unprotect(encryptedData,Scope);
return encryptedData;
}
public override bool IsReprotectRequired(byte[] encryptedData)
{
// For now, this cannot be determined so always return true.
return true;
}
// Public constructor
// The Demand for DataProtectionPermission is in the constructor because we Assert this permission
// in the ProviderProtect/ProviderUnprotect methods.
[DataProtectionPermission(SecurityAction.Demand, Unrestricted = true)]
[SecuritySafeCritical]
public MemoryProtector(string appName, string primaryPurpose, params string[] specificPurpose)
: base(appName, primaryPurpose, specificPurpose)
{
}
}
}
Imports System.Security
Imports System.Security.Permissions
Imports System.Security.Cryptography
Public NotInheritable Class MemoryProtector
Inherits DataProtector
Public Property Scope() As MemoryProtectionScope
Get
Return Scope
End Get
Set(value As MemoryProtectionScope)
End Set
End Property
Protected Overrides ReadOnly Property PrependHashedPurposeToPlaintext() As Boolean
Get
' Signal the DataProtector to prepend the hash of the purpose to the data.
Return True
End Get
End Property
' To allow a service to hand out instances of a DataProtector we demand unrestricted DataProtectionPermission
' in the constructor, but Assert the permission when ProviderProtect is called. This is similar to FileStream
' where access is checked at time of creation, not time of use.
<SecuritySafeCritical(), DataProtectionPermission(SecurityAction.Assert, ProtectData:=True)> _
Protected Overrides Function ProviderProtect(ByVal userData() As Byte) As Byte()
' Delegate to ProtectedData
ProtectedMemory.Protect(userData, Scope)
Return userData
End Function 'ProviderProtect
' To allow a service to hand out instances of a DataProtector we demand unrestricted DataProtectionPermission
' in the constructor, but Assert the permission when ProviderUnprotect is called.. This is similar to FileStream
' where access is checked at time of creation, not time of use.
<SecuritySafeCritical(), DataProtectionPermission(SecurityAction.Assert, UnprotectData:=True)> _
Protected Overrides Function ProviderUnprotect(ByVal encryptedData() As Byte) As Byte()
ProtectedMemory.Unprotect(encryptedData, Scope)
Return encryptedData
End Function 'ProviderUnprotect
Public Overrides Function IsReprotectRequired(ByVal encryptedData() As Byte) As Boolean
' For now, this cannot be determined so always return true.
Return True
End Function 'IsReprotectRequired
' Public constructor
' The Demand for DataProtectionPermission is in the constructor because we Assert this permission
' in the ProviderProtect/ProviderUnprotect methods.
<DataProtectionPermission(SecurityAction.Demand, Unrestricted:=True), SecuritySafeCritical()> _
Public Sub New(ByVal appName As String, ByVal primaryPurpose As String, ParamArray specificPurpose() As String)
MyBase.New(appName, primaryPurpose, specificPurpose)
End Sub
End Class
Observações
Esta classe protege os dados armazenados contra visualização e adulteração. O acesso aos dados protegidos é obtido criando uma instância desta classe e utilizando as strings de propósito exatas que foram usadas para proteger os dados. O chamador não precisa de uma chave para proteger ou desproteger os dados. A chave é fornecida pelo algoritmo de encriptação.
As classes derivadas devem sobrepor os ProviderProtect métodos e, Unprotect que a DataProtector classe base chama de volta. Devem também sobrescrever o IsReprotectRequired método, que pode sempre regressar true com uma potencial pequena perda de eficiência quando as aplicações atualizam a base de dados de texto cifrado armazenado. As classes derivadas devem fornecer um construtor que chame o construtor da classe base, que define as ApplicationNamepropriedades , SpecificPurposes, e PrimaryPurpose .
Construtores
| Name | Description |
|---|---|
| DataProtector(String, String, String[]) |
Cria uma nova instância da DataProtector classe usando o nome da aplicação fornecido, o propósito principal e os propósitos específicos. |
Propriedades
| Name | Description |
|---|---|
| ApplicationName |
Obtém o nome da candidatura. |
| PrependHashedPurposeToPlaintext |
Especifica se o hash é antecedido ao array de texto antes da encriptação. |
| PrimaryPurpose |
Obtém o propósito principal dos dados protegidos. |
| SpecificPurposes |
Obtém os propósitos específicos dos dados protegidos. |
Métodos
| Name | Description |
|---|---|
| Create(String, String, String, String[]) |
Cria uma instância de implementação de protetor de dados utilizando o nome de classe especificado do protetor de dados, o nome da aplicação, o propósito principal e os propósitos específicos. |
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual. (Herdado de Object) |
| GetHashCode() |
Serve como função de hash predefinida. (Herdado de Object) |
| GetHashedPurpose() |
Cria um hash dos valores das propriedades especificados pelo construtor. |
| GetType() |
Obtém o Type da instância atual. (Herdado de Object) |
| IsReprotectRequired(Byte[]) |
Determina se é necessária reencriptação para os dados encriptados especificados. |
| MemberwiseClone() |
Cria uma cópia superficial do atual Object. (Herdado de Object) |
| Protect(Byte[]) |
Protege os dados do utilizador especificados. |
| ProviderProtect(Byte[]) |
Especifica o método delegado na classe derivada para o qual o Protect(Byte[]) método na classe base chama de volta. |
| ProviderUnprotect(Byte[]) |
Especifica o método delegado na classe derivada para o qual o Unprotect(Byte[]) método na classe base chama de volta. |
| ToString() |
Devolve uma cadeia que representa o objeto atual. (Herdado de Object) |
| Unprotect(Byte[]) |
Desprotege os dados protegidos especificados. |