ProtectedData 클래스

정의

데이터를 암호화하거나 해독하는 메서드를 제공합니다. 이 클래스는 상속될 수 없습니다.

public ref class ProtectedData abstract sealed
public ref class ProtectedData sealed
public static class ProtectedData
public sealed class ProtectedData
type ProtectedData = class
Public Class ProtectedData
Public NotInheritable Class ProtectedData
상속
ProtectedData

예제

다음 예제에서는 데이터 보호를 사용 하는 방법을 보여 줍니다.

#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_additionalEntropy = {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_additionalEntropy, 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_additionalEntropy, 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_additionalEntropy = { 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_additionalEntropy, 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_additionalEntropy, 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_additionalEntropy 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_additionalEntropy, 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_additionalEntropy, 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 운영 체제에서 사용할 수 있는 DPAPI(Data Protection API)에 대한 액세스를 제공합니다. 추가 라이브러리가 필요 하지 않습니다 하 고 운영 체제에서 제공 되는 서비스입니다. 사용자 또는 컴퓨터 자격 증명을 사용하여 데이터를 암호화하거나 암호 해독하는 보호를 제공합니다.

중요

DPAPI ProtectedData 에 따라 달라지므로 클래스는 Windows 플랫폼에서만 지원됩니다. Windows PlatformNotSupportedException이외의 플랫폼에서 .NET Core를 사용하면 .

클래스는 관리 되지 않는 DPAPI에 대 한 두 래퍼 이루어져 ProtectUnprotect입니다. 이러한 두 메서드를 사용하여 암호, 키 및 연결 문자열과 같은 데이터를 암호화하고 암호 해독할 수 있습니다.

가장하는 동안 이러한 메서드를 사용하는 경우 "키가 지정된 상태에서 사용할 수 없습니다."라는 오류가 표시될 수 있습니다. 이는 DPAPI가 키 데이터를 사용자 프로필에 저장하기 때문에 발생합니다. 프로필이 로드되지 않은 경우 DPAPI는 암호 해독을 수행할 수 없습니다. 이 오류를 방지하려면 두 방법 중 하나를 호출하기 전에 가장하려는 사용자의 프로필을 로드합니다. 가장과 함께 DPAPI를 사용하면 상당한 복잡성이 발생할 수 있으며 신중한 디자인 선택이 필요합니다.

메서드

Protect(Byte[], Byte[], DataProtectionScope)

지정된 바이트 배열에 있는 데이터를 암호화하고 암호화된 데이터가 포함된 바이트 배열을 반환합니다.

Unprotect(Byte[], Byte[], DataProtectionScope)

지정된 바이트 배열에 있는 데이터를 해독하고 해독된 데이터가 포함된 바이트 배열을 반환합니다.

적용 대상