ProtectedData ProtectedData ProtectedData ProtectedData Class

定义

提供用于加密和解密数据的方法。Provides methods for encrypting and decrypting data. 此类不能被继承。This class cannot be inherited.

public ref class ProtectedData sealed
public sealed class ProtectedData
type ProtectedData = class
Public NotInheritable Class ProtectedData
继承
ProtectedDataProtectedDataProtectedDataProtectedData

示例

下面的示例演示如何使用数据保护。The following example shows how to use data protection.

#using <System.Security.dll>

using namespace System;
using namespace System::Security::Cryptography;

public ref class DataProtectionSample
{
private:

   // Create byte array for additional entropy when using Protect method.
   static array<Byte>^s_aditionalEntropy = {9,8,7,6,5};

public:
   static void Main()
   {
      
      // Create a simple byte array containing data to be encrypted.
      array<Byte>^secret = {0,1,2,3,4,1,2,3,4};
      
      //Encrypt the data.
      array<Byte>^encryptedSecret = Protect( secret );
      Console::WriteLine( "The encrypted byte array is:" );
      PrintValues( encryptedSecret );
      
      // Decrypt the data and store in a byte array.
      array<Byte>^originalData = Unprotect( encryptedSecret );
      Console::WriteLine( "{0}The original data is:", Environment::NewLine );
      PrintValues( originalData );
   }

   static array<Byte>^ Protect( array<Byte>^data )
   {
      try
      {
         
         // Encrypt the data using DataProtectionScope.CurrentUser. The result can be decrypted
         //  only by the same current user.
         return ProtectedData::Protect( data, s_aditionalEntropy, DataProtectionScope::CurrentUser );
      }
      catch ( CryptographicException^ e ) 
      {
         Console::WriteLine( "Data was not encrypted. An error occurred." );
         Console::WriteLine( e );
         return nullptr;
      }
   }

   static array<Byte>^ Unprotect( array<Byte>^data )
   {
      try
      {
         
         //Decrypt the data using DataProtectionScope.CurrentUser.
         return ProtectedData::Unprotect( data, s_aditionalEntropy, DataProtectionScope::CurrentUser );
      }
      catch ( CryptographicException^ e ) 
      {
         Console::WriteLine( "Data was not decrypted. An error occurred." );
         Console::WriteLine( e );
         return nullptr;
      }
   }

   static void PrintValues( array<Byte>^myArr )
   {
      System::Collections::IEnumerator^ myEnum = myArr->GetEnumerator();
      while ( myEnum->MoveNext() )
      {
         Byte i = safe_cast<Byte>(myEnum->Current);
         Console::Write( "\t{0}", i );
      }

      Console::WriteLine();
   }
};

int main()
{
   DataProtectionSample::Main();
}
using System;
using System.Security.Cryptography;

public class DataProtectionSample
{
    // Create byte array for additional entropy when using Protect method.
    static byte [] s_aditionalEntropy = { 9, 8, 7, 6, 5 };

    public static void Main()
    {
        // Create a simple byte array containing data to be encrypted.
        byte [] secret = { 0, 1, 2, 3, 4, 1, 2, 3, 4 };

        //Encrypt the data.
        byte [] encryptedSecret = Protect( secret );
        Console.WriteLine("The encrypted byte array is:");
        PrintValues(encryptedSecret);

        // Decrypt the data and store in a byte array.
        byte [] originalData = Unprotect( encryptedSecret );
        Console.WriteLine("{0}The original data is:", Environment.NewLine);
        PrintValues(originalData);
    }

    public static byte [] Protect( byte [] data )
    {
        try
        {
            // Encrypt the data using DataProtectionScope.CurrentUser. The result can be decrypted
            // only by the same current user.
            return ProtectedData.Protect( data, s_aditionalEntropy, DataProtectionScope.CurrentUser );
        } 
        catch (CryptographicException e)
        {
            Console.WriteLine("Data was not encrypted. An error occurred.");
            Console.WriteLine(e.ToString());
            return null;
        }
    }

    public static byte [] Unprotect( byte [] data )
    {
        try
        {
            //Decrypt the data using DataProtectionScope.CurrentUser.
            return ProtectedData.Unprotect( data, s_aditionalEntropy, DataProtectionScope.CurrentUser );
        } 
        catch (CryptographicException e)
        {
            Console.WriteLine("Data was not decrypted. An error occurred.");
            Console.WriteLine(e.ToString());
            return null;
        }
    }

    public static void PrintValues( Byte[] myArr )  
    {
        foreach ( Byte i in myArr )  
        {
            Console.Write( "\t{0}", i );
        }
        Console.WriteLine();
    }
}
Imports System.Security.Cryptography



Public Class DataProtectionSample
    ' Create byte array for additional entropy when using Protect method.
    Private Shared s_aditionalEntropy As Byte() = {9, 8, 7, 6, 5}


    Public Shared Sub Main()
        ' Create a simple byte array containing data to be encrypted.
        Dim secret As Byte() = {0, 1, 2, 3, 4, 1, 2, 3, 4}

        'Encrypt the data.
        Dim encryptedSecret As Byte() = Protect(secret)
        Console.WriteLine("The encrypted byte array is:")
        PrintValues(encryptedSecret)

        ' Decrypt the data and store in a byte array.
        Dim originalData As Byte() = Unprotect(encryptedSecret)
        Console.WriteLine("{0}The original data is:", Environment.NewLine)
        PrintValues(originalData)

    End Sub


    Public Shared Function Protect(ByVal data() As Byte) As Byte()
        Try
            ' Encrypt the data using DataProtectionScope.CurrentUser. The result can be decrypted
            '  only by the same current user.
            Return ProtectedData.Protect(data, s_aditionalEntropy, DataProtectionScope.CurrentUser)
        Catch e As CryptographicException
            Console.WriteLine("Data was not encrypted. An error occurred.")
            Console.WriteLine(e.ToString())
            Return Nothing
        End Try

    End Function


    Public Shared Function Unprotect(ByVal data() As Byte) As Byte()
        Try
            'Decrypt the data using DataProtectionScope.CurrentUser.
            Return ProtectedData.Unprotect(data, s_aditionalEntropy, DataProtectionScope.CurrentUser)
        Catch e As CryptographicException
            Console.WriteLine("Data was not decrypted. An error occurred.")
            Console.WriteLine(e.ToString())
            Return Nothing
        End Try

    End Function


    Public Shared Sub PrintValues(ByVal myArr() As [Byte])
        Dim i As [Byte]
        For Each i In myArr
            Console.Write(vbTab + "{0}", i)
        Next i
        Console.WriteLine()

    End Sub
End Class

注解

此类提供对 Windows 操作系统中可用的数据保护 API (DPAPI) 的访问权限。This class provides access to the Data Protection API (DPAPI) available in Windows operating systems. 这是由操作系统提供的服务, 不需要其他库。This is a service that is provided by the operating system and does not require additional libraries. 它使用用户或计算机凭据提供保护, 以对数据进行加密或解密。It provides protection using the user or machine credentials to encrypt or decrypt data.

重要

由于它依赖于 DPAPI, 因此ProtectedData仅在 Windows 平台上支持此类。Because it depends on DPAPI, the ProtectedData class is supported on the Windows platform only. 它在非 Windows 平台上的 .NET Core 中使用会PlatformNotSupportedException引发。Its use on .NET Core on platforms other than Windows throws a PlatformNotSupportedException.

此类包含两个非托管 DPAPI ProtectUnprotect的包装器。The class consists of two wrappers for the unmanaged DPAPI, Protect and Unprotect. 这两种方法可用于对数据进行加密和解密, 如密码、密钥和连接字符串。These two methods can be used to encrypt and decrypt data such as passwords, keys, and connection strings.

如果在模拟期间使用这些方法, 则可能会收到以下错误:"键在指定的状态中使用时无效。"If you use these methods during impersonation, you may receive the following error: "Key not valid for use in specified state." 之所以发生这种情况, 是因为 DPAPI 将密钥数据存储在用户配置文件中。This occurs because the DPAPI stores the key data in user profiles. 如果未加载配置文件, 则 DPAPI 将无法执行解密。If the profile is not loaded, DPAPI won't be able to perform the decryption. 若要避免此错误, 请在调用任一方法之前加载要模拟的用户的配置文件。To prevent this error, load the profile of the user you want to impersonate before calling either method. 将 DPAPI 与模拟结合使用可能会产生很大的影响, 需要小心设计。Using DPAPI with impersonation can incur significant complication and requires careful design choices.

方法

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

获取当前实例的 TypeGets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(Inherited from Object)
Protect(Byte[], Byte[], DataProtectionScope) Protect(Byte[], Byte[], DataProtectionScope) Protect(Byte[], Byte[], DataProtectionScope) Protect(Byte[], Byte[], DataProtectionScope)

在指定的字节数组中加密数据,并返回包含已加密数据的字节数组。Encrypts the data in a specified byte array and returns a byte array that contains the encrypted data.

ToString() ToString() ToString() ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(Inherited from Object)
Unprotect(Byte[], Byte[], DataProtectionScope) Unprotect(Byte[], Byte[], DataProtectionScope) Unprotect(Byte[], Byte[], DataProtectionScope) Unprotect(Byte[], Byte[], DataProtectionScope)

在指定的字节数组中解密数据,并返回包含已解密数据的字节数组。Decrypts the data in a specified byte array and returns a byte array that contains the decrypted data.

适用于