DataProtector Класс

Определение

Предоставляет базовый класс для предохранителей данных.

public ref class DataProtector abstract
public abstract class DataProtector
type DataProtector = class
Public MustInherit Class DataProtector
Наследование
DataProtector
Производный

Примеры

В следующем примере показано, как создать средство защиты данных, использующее класс защиты с параметром для дополнительной энтропии. По умолчанию DataProtector класс добавляет хэш свойств назначения к зашифрованным данным. Вы можете отключить эту функцию и использовать хэшированную цель как дополнительную энтропию при вызове средства защиты данных с дополнительным параметром энтропии.

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

В следующем примере показана простая защита данных, использующая функциональные PrependHashedPurposeToPlaintextDataProtector возможности класса .

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

Комментарии

Этот класс защищает сохраненные данные от просмотра и незаконного изменения. Доступ к защищенным данным получается путем создания экземпляра этого класса и использования строк точного назначения, которые использовались для защиты данных. Вызывающей объекту не требуется ключ для защиты или отмены защиты данных. Ключ предоставляется алгоритмом шифрования.

Производные классы должны переопределять ProviderProtect методы и Unprotect , которые базовый DataProtector класс вызывает обратно. Они также должны переопределить IsReprotectRequired метод , который всегда может возвращать true с небольшой потерей эффективности, когда приложения обновляют свою базу данных сохраненного зашифрованного текста. Производные классы должны предоставлять конструктор, вызывающий конструктор базового класса, который задает ApplicationNameсвойства , SpecificPurposesи PrimaryPurpose .

Конструкторы

DataProtector(String, String, String[])

Создает новый экземпляр класса DataProtector, используя предоставленное имя приложения, первичную цель и определенные цели.

Свойства

ApplicationName

Возвращает имя приложения.

PrependHashedPurposeToPlaintext

Определяет, добавляется ли хэш в начало массива текста перед шифрованием.

PrimaryPurpose

Получает основное назначение для защищенных данных.

SpecificPurposes

Получает определенное назначение для защищенных данных.

Методы

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

Создает экземпляр реализации предохранителя данных с помощью указанного имени класса предохранителя данных, имени приложения, первичной цели и определенных целей.

Equals(Object)

Определяет, равен ли указанный объект текущему объекту.

(Унаследовано от Object)
GetHashCode()

Служит хэш-функцией по умолчанию.

(Унаследовано от Object)
GetHashedPurpose()

Создает хэш значений свойств, определяемых конструктором.

GetType()

Возвращает объект Type для текущего экземпляра.

(Унаследовано от Object)
IsReprotectRequired(Byte[])

Указывает, необходимо ли перешифрование для указанных зашифрованных данных.

MemberwiseClone()

Создает неполную копию текущего объекта Object.

(Унаследовано от Object)
Protect(Byte[])

Защищает заданные пользовательские данные.

ProviderProtect(Byte[])

Задает метод делегата в производном классе, в адрес которого метод Protect(Byte[]) в базовом классе выполняет обратный вызов.

ProviderUnprotect(Byte[])

Задает метод делегата в производном классе, в адрес которого метод Unprotect(Byte[]) в базовом классе выполняет обратный вызов.

ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)
Unprotect(Byte[])

Снимает защиту с указанных защищенных данных.

Применяется к