Share via


HOW TO:使用資料保護

.NET Framework 提供資料保護 API (DPAPI) 的存取,可以讓您使用目前使用者帳戶或電腦的資訊,為資料加密。 當您使用 DPAPI 時,您會減低要明確產生並儲存加密金鑰的難度。

請使用 ProtectedMemory 類別,為 In-Memory 位元組陣列加密。 這項功能可以在 Microsoft Windows XP (含) 以後版本的作業系統中使用。 您可以指定:由目前處理序加密的記憶體只能由目前處理序、所有處理序,或是從相同使用者內容加以解密。 如需 ProtectedMemory 選項的詳細描述,請參閱 MemoryProtectionScope 列舉型別。

請使用 ProtectedData 類別,為位元組陣列的複本加密。 這項功能可以在 Microsoft Windows 2000 以上版本的作業系統中使用。 您可以指定:由目前使用者帳戶加密的資料只能由相同的使用者帳戶加以解密,或是您也可以指定:由目前使用者帳戶加密的資料能夠由電腦上任何帳戶加以解密。 如需 ProtectedData 選項的詳細描述,請參閱 DataProtectionScope 列舉型別。

若要使用資料保護為 In-Memory 資料加密

  • 傳遞要加密的位元組陣列、Entropy 和記憶體保護範圍時,呼叫靜態 Protect 方法。

若要使用資料保護為 In-Memory 資料解密

  • 傳遞要解密的位元組陣列和記憶體保護範圍時,呼叫靜態 Unprotect 方法。

若要使用資料保護將資料加密至檔案或資料流

  1. 建立隨機 Entropy。

  2. 傳遞要加密的位元組陣列、Entropy 和記憶體保護範圍時,呼叫靜態 Protect 方法。

  3. 將加密資料寫入檔案或資料流。

若要使用資料保護將資料解密至檔案或資料流

  1. 從檔案或資料流讀取加密資料。

  2. 傳遞要解密的位元組陣列和資料保護範圍時,呼叫靜態 Unprotect 方法。

範例

下列程式碼範例會示範兩種加密和解密的形式。 程式碼範例會將 In-Memory 位元組陣列加密然後再解密。 接下來,程式碼範例會為位元組陣列的複本加密再儲存至檔案,然後從檔案將資料載回再為資料解密。 此範例會顯示原始資料、加密後的資料,以及解密後的資料。

Imports System
Imports System.IO
Imports System.Text
Imports System.Security.Cryptography



Public Module MemoryProtectionSample

    Sub Main()
        Run()

    End Sub 'Main


    Sub Run()
        Try

            ''''''''''''''''''''''''''''''''''''
            '
            ' Memory Encryption - ProtectedMemory
            '
            ''''''''''''''''''''''''''''''''''''
            ' Create the original data to be encrypted (The data length should be a multiple of 16).
            Dim toEncrypt As Byte() = UnicodeEncoding.ASCII.GetBytes("ThisIsSomeData16")

            Console.WriteLine("Original data: " + UnicodeEncoding.ASCII.GetString(toEncrypt))
            Console.WriteLine("Encrypting...")

            ' Encrypt the data in memory.
            EncryptInMemoryData(toEncrypt, MemoryProtectionScope.SameLogon)

            Console.WriteLine("Encrypted data: " + UnicodeEncoding.ASCII.GetString(toEncrypt))
            Console.WriteLine("Decrypting...")

            ' Decrypt the data in memory.
            DecryptInMemoryData(toEncrypt, MemoryProtectionScope.SameLogon)

            Console.WriteLine("Decrypted data: " + UnicodeEncoding.ASCII.GetString(toEncrypt))


            ''''''''''''''''''''''''''''''''''''
            '
            ' Data Encryption - ProtectedData
            '
            ''''''''''''''''''''''''''''''''''''
            ' Create the original data to be encrypted
            toEncrypt = UnicodeEncoding.ASCII.GetBytes("This is some data of any length.")

            ' Create a file.
            Dim fStream As New FileStream("Data.dat", FileMode.OpenOrCreate)

            ' Create some random entropy.
            Dim entropy As Byte() = CreateRandomEntropy()

            Console.WriteLine()
            Console.WriteLine("Original data: " + UnicodeEncoding.ASCII.GetString(toEncrypt))
            Console.WriteLine("Encrypting and writing to disk...")

            ' Encrypt a copy of the data to the stream.
            Dim bytesWritten As Integer = EncryptDataToStream(toEncrypt, entropy, DataProtectionScope.CurrentUser, fStream)

            fStream.Close()

            Console.WriteLine("Reading data from disk and decrypting...")

            ' Open the file.
            fStream = New FileStream("Data.dat", FileMode.Open)

            ' Read from the stream and decrypt the data.
            Dim decryptData As Byte() = DecryptDataFromStream(entropy, DataProtectionScope.CurrentUser, fStream, bytesWritten)

            fStream.Close()

            Console.WriteLine("Decrypted data: " + UnicodeEncoding.ASCII.GetString(decryptData))


        Catch e As Exception
            Console.WriteLine("ERROR: " + e.Message)
        End Try

    End Sub 'Run



    Sub EncryptInMemoryData(ByVal Buffer() As Byte, ByVal Scope As MemoryProtectionScope)
        If Buffer.Length <= 0 Then
            Throw New ArgumentException("Buffer")
        End If
        If Buffer Is Nothing Then
            Throw New ArgumentNullException("Buffer")
        End If

        ' Encrypt the data in memory. The result is stored in the same same array as the original data.
        ProtectedMemory.Protect(Buffer, Scope)

    End Sub 'EncryptInMemoryData


    Sub DecryptInMemoryData(ByVal Buffer() As Byte, ByVal Scope As MemoryProtectionScope)
        If Buffer.Length <= 0 Then
            Throw New ArgumentException("Buffer")
        End If
        If Buffer Is Nothing Then
            Throw New ArgumentNullException("Buffer")
        End If

        ' Decrypt the data in memory. The result is stored in the same same array as the original data.
        ProtectedMemory.Unprotect(Buffer, Scope)

    End Sub 'DecryptInMemoryData


    Function CreateRandomEntropy() As Byte()
        ' Create a byte array to hold the random value.
        Dim entropy(15) As Byte

        ' Create a new instance of the RNGCryptoServiceProvider.
        ' Fill the array with a random value.
        Dim RNG As New RNGCryptoServiceProvider()

        RNG.GetBytes(entropy)

        ' Return the array.
        Return entropy

    End Function 'CreateRandomEntropy



    Function EncryptDataToStream(ByVal Buffer() As Byte, ByVal Entropy() As Byte, ByVal Scope As DataProtectionScope, ByVal S As Stream) As Integer
        If Buffer.Length <= 0 Then
            Throw New ArgumentException("Buffer")
        End If
        If Buffer Is Nothing Then
            Throw New ArgumentNullException("Buffer")
        End If
        If Entropy.Length <= 0 Then
            Throw New ArgumentException("Entropy")
        End If
        If Entropy Is Nothing Then
            Throw New ArgumentNullException("Entropy")
        End If
        If S Is Nothing Then
            Throw New ArgumentNullException("S")
        End If
        Dim length As Integer = 0

        ' Encrypt the data in memory. The result is stored in the same same array as the original data.
        Dim encrptedData As Byte() = ProtectedData.Protect(Buffer, Entropy, Scope)

        ' Write the encrypted data to a stream.
        If S.CanWrite AndAlso Not (encrptedData Is Nothing) Then
            S.Write(encrptedData, 0, encrptedData.Length)

            length = encrptedData.Length
        End If

        ' Return the length that was written to the stream. 
        Return length

    End Function 'EncryptDataToStream


    Function DecryptDataFromStream(ByVal Entropy() As Byte, ByVal Scope As DataProtectionScope, ByVal S As Stream, ByVal Length As Integer) As Byte()
        If S Is Nothing Then
            Throw New ArgumentNullException("S")
        End If
        If Length <= 0 Then
            Throw New ArgumentException("Length")
        End If
        If Entropy Is Nothing Then
            Throw New ArgumentNullException("Entropy")
        End If
        If Entropy.Length <= 0 Then
            Throw New ArgumentException("Entropy")
        End If


        Dim inBuffer(Length) As Byte
        Dim outBuffer() As Byte

        ' Read the encrypted data from a stream.
        If S.CanRead Then
            S.Read(inBuffer, 0, Length)

            outBuffer = ProtectedData.Unprotect(inBuffer, Entropy, Scope)
        Else
            Throw New IOException("Could not read the stream.")
        End If

        ' Return the length that was written to the stream. 
        Return outBuffer

    End Function 'DecryptDataFromStream 
End Module 'MemoryProtectionSample
using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;

public class MemoryProtectionSample
{
    public static void Main()
    {
        Run();
    }

    public static void Run()
    {
        try
        {

            ///////////////////////////////
            //
            // Memory Encryption - ProtectedMemory
            //
            ///////////////////////////////

            // Create the original data to be encrypted (The data length should be a multiple of 16).
            byte[] toEncrypt = UnicodeEncoding.ASCII.GetBytes("ThisIsSomeData16");

            Console.WriteLine("Original data: " + UnicodeEncoding.ASCII.GetString(toEncrypt));
            Console.WriteLine("Encrypting...");

            // Encrypt the data in memory.
            EncryptInMemoryData(toEncrypt, MemoryProtectionScope.SameLogon);

            Console.WriteLine("Encrypted data: " + UnicodeEncoding.ASCII.GetString(toEncrypt));
            Console.WriteLine("Decrypting...");

            // Decrypt the data in memory.
            DecryptInMemoryData(toEncrypt, MemoryProtectionScope.SameLogon);

            Console.WriteLine("Decrypted data: " + UnicodeEncoding.ASCII.GetString(toEncrypt));


            ///////////////////////////////
            //
            // Data Encryption - ProtectedData
            //
            ///////////////////////////////

            // Create the original data to be encrypted
            toEncrypt = UnicodeEncoding.ASCII.GetBytes("This is some data of any length.");

            // Create a file.
            FileStream fStream = new FileStream("Data.dat", FileMode.OpenOrCreate);

            // Create some random entropy.
            byte[] entropy = CreateRandomEntropy();

            Console.WriteLine();
            Console.WriteLine("Original data: " + UnicodeEncoding.ASCII.GetString(toEncrypt));
            Console.WriteLine("Encrypting and writing to disk...");

            // Encrypt a copy of the data to the stream.
            int bytesWritten = EncryptDataToStream(toEncrypt, entropy, DataProtectionScope.CurrentUser, fStream);

            fStream.Close();

            Console.WriteLine("Reading data from disk and decrypting...");

            // Open the file.
            fStream = new FileStream("Data.dat", FileMode.Open);

            // Read from the stream and decrypt the data.
            byte[] decryptData = DecryptDataFromStream(entropy, DataProtectionScope.CurrentUser, fStream, bytesWritten);

            fStream.Close();

            Console.WriteLine("Decrypted data: " + UnicodeEncoding.ASCII.GetString(decryptData));


        }
        catch (Exception e)
        {
            Console.WriteLine("ERROR: " + e.Message);
        }

    }


    public static void EncryptInMemoryData(byte[] Buffer, MemoryProtectionScope Scope )
    {
        if (Buffer.Length <= 0)
            throw new ArgumentException("Buffer");
        if (Buffer == null)
            throw new ArgumentNullException("Buffer");


        // Encrypt the data in memory. The result is stored in the same same array as the original data.
        ProtectedMemory.Protect(Buffer, Scope);

    }

    public static void DecryptInMemoryData(byte[] Buffer, MemoryProtectionScope Scope)
    {
        if (Buffer.Length <= 0)
            throw new ArgumentException("Buffer");
        if (Buffer == null)
            throw new ArgumentNullException("Buffer");


        // Decrypt the data in memory. The result is stored in the same same array as the original data.
        ProtectedMemory.Unprotect(Buffer, Scope);

    }

    public static byte[] CreateRandomEntropy()
    {
        // Create a byte array to hold the random value.
        byte[] entropy = new byte[16];

        // Create a new instance of the RNGCryptoServiceProvider.
        // Fill the array with a random value.
        new RNGCryptoServiceProvider().GetBytes(entropy);

        // Return the array.
        return entropy;


    }

    public static int EncryptDataToStream(byte[] Buffer, byte[] Entropy, DataProtectionScope Scope, Stream S)
    {
        if (Buffer.Length <= 0)
            throw new ArgumentException("Buffer");
        if (Buffer == null)
            throw new ArgumentNullException("Buffer");
        if (Entropy.Length <= 0)
            throw new ArgumentException("Entropy");
        if (Entropy == null)
            throw new ArgumentNullException("Entropy");
        if (S == null)
            throw new ArgumentNullException("S");

        int length = 0;

        // Encrypt the data in memory. The result is stored in the same same array as the original data.
        byte[] encrptedData = ProtectedData.Protect(Buffer, Entropy, Scope);

        // Write the encrypted data to a stream.
        if (S.CanWrite && encrptedData != null)
        {
            S.Write(encrptedData, 0, encrptedData.Length);

            length = encrptedData.Length;
        }

        // Return the length that was written to the stream. 
        return length;

    }

    public static byte[] DecryptDataFromStream(byte[] Entropy, DataProtectionScope Scope, Stream S, int Length)
    {
        if (S == null)
            throw new ArgumentNullException("S");
        if (Length <= 0 )
            throw new ArgumentException("Length");
        if (Entropy == null)
            throw new ArgumentNullException("Entropy");
        if (Entropy.Length <= 0)
            throw new ArgumentException("Entropy");



        byte[] inBuffer = new byte[Length];
        byte[] outBuffer;

        // Read the encrypted data from a stream.
        if (S.CanRead)
        {
            S.Read(inBuffer, 0, Length);

            outBuffer = ProtectedData.Unprotect(inBuffer, Entropy, Scope);
        }
        else
        {
            throw new IOException("Could not read the stream.");
        }

        // Return the length that was written to the stream. 
        return outBuffer;

    }


}

編譯程式碼

請參閱

參考

ProtectedMemory

ProtectedData

其他資源

密碼編譯工作