DataProtector Clase
Definición
Importante
Parte de la información hace referencia a la versión preliminar del producto, que puede haberse modificado sustancialmente antes de lanzar la versión definitiva. Microsoft no otorga ninguna garantía, explícita o implícita, con respecto a la información proporcionada aquí.
Proporciona la clase base para los protectores de datos.
public ref class DataProtector abstract
public abstract class DataProtector
type DataProtector = class
Public MustInherit Class DataProtector
- Herencia
-
DataProtector
- Derivado
Ejemplos
En el ejemplo siguiente se muestra cómo crear un protector de datos que use una clase de protección con una opción para la entropía adicional. De forma predeterminada, la DataProtector clase antepone el hash de las propiedades de propósito a los datos que se van a cifrar. Puede desactivar esa funcionalidad y usar el propósito hash como entropía adicional al llamar a un protector de datos con una opción de entropía adicional.
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
En el ejemplo siguiente se muestra un protector de datos simple que usa la PrependHashedPurposeToPlaintext funcionalidad de la DataProtector clase .
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
Comentarios
Esta clase protege los datos almacenados frente a la visualización y manipulación. El acceso a los datos protegidos se obtiene mediante la creación de una instancia de esta clase y el uso de las cadenas de propósito exactas que se usaron para proteger los datos. El autor de la llamada no necesita una clave para proteger o desproteger los datos. El algoritmo de cifrado proporciona la clave.
Las clases derivadas deben invalidar los ProviderProtect métodos y Unprotect en los que la DataProtector clase base vuelve a llamar. También deben invalidar el IsReprotectRequired método , que siempre puede devolver true
con una posible pérdida de eficacia cuando las aplicaciones actualizan su base de datos de texto cifrado almacenado. Las clases derivadas deben proporcionar un constructor que llame al constructor de clase base, que establece las ApplicationNamepropiedades , SpecificPurposesy PrimaryPurpose .
Constructores
DataProtector(String, String, String[]) |
Crea una nueva instancia de la clase DataProtector utilizando el nombre de aplicación, el propósito principal y los propósitos concretos proporcionados. |
Propiedades
ApplicationName |
Obtiene el nombre de la aplicación. |
PrependHashedPurposeToPlaintext |
Especifica si el elemento hash se antepone a la matriz de texto antes del cifrado. |
PrimaryPurpose |
Obtiene el propósito principal de los datos protegidos. |
SpecificPurposes |
Obtiene los propósitos específicos para los datos protegidos. |
Métodos
Create(String, String, String, String[]) |
Crea una instancia de una implementación de protector de datos utilizando el nombre de clase del protector de datos, el nombre de la aplicación, el propósito principal y los propósitos concretos especificados. |
Equals(Object) |
Determina si el objeto especificado es igual que el objeto actual. (Heredado de Object) |
GetHashCode() |
Sirve como la función hash predeterminada. (Heredado de Object) |
GetHashedPurpose() |
Crea un hash de los valores de propiedad especificados por el constructor. |
GetType() |
Obtiene el Type de la instancia actual. (Heredado de Object) |
IsReprotectRequired(Byte[]) |
Determina si es preciso volver a cifrar los datos cifrados especificados. |
MemberwiseClone() |
Crea una copia superficial del Object actual. (Heredado de Object) |
Protect(Byte[]) |
Protege los datos especificados pro el usuario. |
ProviderProtect(Byte[]) |
Especifica el método delegado de la clase derivada a la que el método Protect(Byte[]) de la clase base devuelve la llamada. |
ProviderUnprotect(Byte[]) |
Especifica el método delegado de la clase derivada a la que el método Unprotect(Byte[]) de la clase base devuelve la llamada. |
ToString() |
Devuelve una cadena que representa el objeto actual. (Heredado de Object) |
Unprotect(Byte[]) |
Desprotege los datos protegidos especificados. |