DataProtector Classe

Definição

Fornece a classe base para protetores de dados.Provides the base class for data protectors.

public ref class DataProtector abstract
public abstract class DataProtector
type DataProtector = class
Public MustInherit Class DataProtector
Herança
DataProtector
Derivado

Exemplos

O exemplo a seguir demonstra como criar um protetor de dados que usa uma classe de proteção com uma opção para entropia extra.The following example demonstrates how to create a data protector that uses a protection class with an option for extra entropy. Por padrão, a DataProtector classe precede o hash das propriedades de finalidade para os dados a serem criptografados.By default, the DataProtector class prepends the hash of the purpose properties to the data to be encrypted. Você pode desativar essa funcionalidade e usar a finalidade com hash como entropia extra ao chamar um protetor de dados com uma opção de entropia adicional.You can turn that functionality off and use the hashed purpose as extra entropy when calling a data protector with an extra entropy option.

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 a seguir demonstra um simples protetor de dados que usa a PrependHashedPurposeToPlaintext funcionalidade da DataProtector classe.The following example demonstrates a simple data protector that uses the PrependHashedPurposeToPlaintext functionality of the DataProtector class.

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

Comentários

Essa classe protege os dados armazenados de exibição e adulteração.This class protects stored data from viewing and tampering. O acesso aos dados protegidos é obtido criando uma instância dessa classe e usando as cadeias de caracteres de finalidade exata que foram usadas para proteger os dados.The access to the protected data is obtained by creating an instance of this class and using the exact purpose strings that were used to protect the data. O chamador não precisa de uma chave para proteger ou desproteger os dados.The caller does not need a key to either protect or unprotect the data. A chave é fornecida pelo algoritmo de criptografia.The key is provided by the encryption algorithm.

Classes derivadas devem substituir os ProviderProtect Unprotect métodos e, que a DataProtector classe base chama de volta para.Derived classes must override the ProviderProtect and Unprotect methods, which the DataProtector base class calls back into. Eles também devem substituir o IsReprotectRequired método, que sempre pode retornar true com uma possível perda pequena de eficiência quando os aplicativos atualizam seu banco de dados de texto cifrado armazenado.They must also override the IsReprotectRequired method, which can always return true with a potential small loss of efficiency when applications refresh their database of stored cipher text. Classes derivadas devem fornecer um construtor que chama o construtor da classe base, que define ApplicationName as SpecificPurposes Propriedades, e PrimaryPurpose .Derived classes should provide a constructor that calls the base class constructor, which sets the ApplicationName, SpecificPurposes, and PrimaryPurpose properties.

Construtores

DataProtector(String, String, String[])

Cria uma nova instância da classe DataProtector usando o nome do aplicativo fornecido, o objetivo principal e as finalidades específicas.Creates a new instance of the DataProtector class by using the provided application name, primary purpose, and specific purposes.

Propriedades

ApplicationName

Obtém o nome do aplicativo.Gets the name of the application.

PrependHashedPurposeToPlaintext

Especifica se o hash é anexado à matriz de texto antes da criptografia.Specifies whether the hash is prepended to the text array before encryption.

PrimaryPurpose

Obtém a finalidade principal dos dados protegidos.Gets the primary purpose for the protected data.

SpecificPurposes

Obtém as finalidades específicas para os dados protegidos.Gets the specific purposes for the protected data.

Métodos

Create(String, String, String, String[])

Cria uma instância de uma implementação de protetor de dados usando o nome de classe especificado do protetor de dados, o nome do aplicativo, a principal finalidade e as finalidades específicas.Creates an instance of a data protector implementation by using the specified class name of the data protector, the application name, the primary purpose, and the specific purposes.

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object.

(Herdado de Object)
GetHashCode()

Serve como a função de hash padrão.Serves as the default hash function.

(Herdado de Object)
GetHashedPurpose()

Cria um hash dos valores de propriedade especificados pelo construtor.Creates a hash of the property values specified by the constructor.

GetType()

Obtém o Type da instância atual.Gets the Type of the current instance.

(Herdado de Object)
IsReprotectRequired(Byte[])

Determina se a nova criptografia é necessária para os dados criptografados especificados.Determines if re-encryption is required for the specified encrypted data.

MemberwiseClone()

Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object.

(Herdado de Object)
Protect(Byte[])

Protege os dados do usuário especificado.Protects the specified user data.

ProviderProtect(Byte[])

Especifica o método delegado na classe derivada que o método Protect(Byte[]) na classe base chama de volta.Specifies the delegate method in the derived class that the Protect(Byte[]) method in the base class calls back into.

ProviderUnprotect(Byte[])

Especifica o método delegado na classe derivada que o método Unprotect(Byte[]) na classe base chama de volta.Specifies the delegate method in the derived class that the Unprotect(Byte[]) method in the base class calls back into.

ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object.

(Herdado de Object)
Unprotect(Byte[])

Desprotege os dados protegidos especificados.Unprotects the specified protected data.

Aplica-se a