CryptoStream 類別

定義

定義連結資料流與密碼編譯轉換的資料流。

public ref class CryptoStream : System::IO::Stream
public class CryptoStream : System.IO.Stream
[System.Runtime.InteropServices.ComVisible(true)]
public class CryptoStream : System.IO.Stream
type CryptoStream = class
    inherit Stream
    interface IDisposable
[<System.Runtime.InteropServices.ComVisible(true)>]
type CryptoStream = class
    inherit Stream
    interface IDisposable
Public Class CryptoStream
Inherits Stream
繼承
CryptoStream
繼承
屬性
實作

範例

下列範例示範如何使用 CryptoStream 來加密字串。 這個方法會使用 類別 Aes 搭配指定的 Key 和 初始化向量, (IV) 。

using System;
using System.IO;
using System.Security.Cryptography;

class AesExample
{
    public static void Main()
    {
        try
        {
            string original = "Here is some data to encrypt!";

            // Create a new instance of the Aes class.
            // This generates a new key and initialization vector (IV).
            using (Aes myAes = Aes.Create())
            {
                // Encrypt the string to an array of bytes.
                byte[] encrypted = EncryptStringToBytes(original, myAes.Key, myAes.IV);

                // Decrypt the bytes to a string.
                string roundtrip = DecryptStringFromBytes(encrypted, myAes.Key, myAes.IV);

                // Display the original data and the decrypted data.
                Console.WriteLine("Original:   {0}", original);
                Console.WriteLine("Round trip: {0}", roundtrip);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Error: {0}", e.Message);
        }
    }

    static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
    {
        // Check arguments.
        if (plainText == null || plainText.Length <= 0)
            throw new ArgumentNullException(nameof(plainText));
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException(nameof(Key));
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException(nameof(IV));
        byte[] encrypted;

        // Create a Aes object with the specified key and IV.
        using (Aes aesAlg = Aes.Create())
        {
            aesAlg.Key = Key;
            aesAlg.IV = IV;

            // Create an encryptor to perform the stream transform.
            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

            // Create the streams used for encryption.
            using (MemoryStream msEncrypt = new())
            {
                using (CryptoStream csEncrypt = new(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new(csEncrypt))
                    {
                        // Write all data to the stream.
                        swEncrypt.Write(plainText);
                    }
                    encrypted = msEncrypt.ToArray();
                }
            }
        }

        // Return the encrypted bytes from the memory stream.
        return encrypted;
    }

    static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
    {
        // Check arguments.
        if (cipherText == null || cipherText.Length <= 0)
            throw new ArgumentNullException(nameof(cipherText));
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException(nameof(Key));
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException(nameof(IV));

        // Declare the string used to hold the decrypted text.
        string plaintext = null;

        // Create a Aes object with the specified key and IV.
        using (Aes aesAlg = Aes.Create())
        {
            aesAlg.Key = Key;
            aesAlg.IV = IV;

            // Create a decryptor to perform the stream transform.
            ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

            // Create the streams used for decryption.
            using (MemoryStream msDecrypt = new(cipherText))
            {
                using (CryptoStream csDecrypt = new(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader srDecrypt = new(csDecrypt))
                    {

                        // Read the decrypted bytes from the decrypting stream
                        // and place them in a string.
                        plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }
        }

        return plaintext;
    }
}
Imports System.IO
Imports System.Security.Cryptography

Class AesExample

    Public Shared Sub Main()
        Try
            Dim original As String = "Here is some data to encrypt!"

            ' Create a new instance of the Aes class.
            ' This generates a new key and initialization vector (IV).
            Using myAes = Aes.Create()

                ' Encrypt the string to an array of bytes.
                Dim encrypted As Byte() = EncryptStringToBytes(original, myAes.Key, myAes.IV)

                ' Decrypt the bytes to a string.
                Dim roundtrip As String = DecryptStringFromBytes(encrypted, myAes.Key, myAes.IV)

                'Display the original data and the decrypted data.
                Console.WriteLine("Original:   {0}", original)
                Console.WriteLine("Round Trip: {0}", roundtrip)
            End Using
        Catch e As Exception
            Console.WriteLine("Error: {0}", e.Message)
        End Try
    End Sub

    Shared Function EncryptStringToBytes(ByVal plainText As String, ByVal Key() As Byte, ByVal IV() As Byte) As Byte()
        ' Check arguments.
        If plainText Is Nothing OrElse plainText.Length <= 0 Then
            Throw New ArgumentNullException(NameOf(plainText))
        End If
        If Key Is Nothing OrElse Key.Length <= 0 Then
            Throw New ArgumentNullException(NameOf(Key))
        End If
        If IV Is Nothing OrElse IV.Length <= 0 Then
            Throw New ArgumentNullException(NameOf(IV))
        End If
        Dim encrypted() As Byte

        ' Create an Aes object with the specified key and IV.
        Using aesAlg = Aes.Create()

            aesAlg.Key = Key
            aesAlg.IV = IV

            ' Create an encryptor to perform the stream transform.
            Dim encryptor As ICryptoTransform = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV)
            ' Create the streams used for encryption.
            Using msEncrypt As New MemoryStream()
                Using csEncrypt As New CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)
                    Using swEncrypt As New StreamWriter(csEncrypt)

                        ' Write all data to the stream.
                        swEncrypt.Write(plainText)
                    End Using
                    encrypted = msEncrypt.ToArray()
                End Using
            End Using
        End Using

        ' Return the encrypted bytes from the memory stream.
        Return encrypted

    End Function 'EncryptStringToBytes

    Shared Function DecryptStringFromBytes(
        ByVal cipherText() As Byte,
        ByVal Key() As Byte,
        ByVal IV() As Byte) As String
        ' Check arguments.
        If cipherText Is Nothing OrElse cipherText.Length <= 0 Then
            Throw New ArgumentNullException(NameOf(cipherText))
        End If
        If Key Is Nothing OrElse Key.Length <= 0 Then
            Throw New ArgumentNullException(NameOf(Key))
        End If
        If IV Is Nothing OrElse IV.Length <= 0 Then
            Throw New ArgumentNullException(NameOf(IV))
        End If

        ' Declare the string used to hold the decrypted text.
        Dim plaintext As String = Nothing

        ' Create an Aes object with the specified key and IV.
        Using aesAlg = Aes.Create()
            aesAlg.Key = Key
            aesAlg.IV = IV

            ' Create a decryptor to perform the stream transform.
            Dim decryptor As ICryptoTransform = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV)

            ' Create the streams used for decryption.
            Using msDecrypt As New MemoryStream(cipherText)
                Using csDecrypt As New CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)
                    Using srDecrypt As New StreamReader(csDecrypt)
                        ' Read the decrypted bytes from the decrypting stream
                        ' and place them in a string.
                        plaintext = srDecrypt.ReadToEnd()
                    End Using
                End Using
            End Using
        End Using

        Return plaintext

    End Function 'DecryptStringFromBytes 
End Class

備註

Common Language Runtime 使用數據流導向的設計進行密碼編譯。 這個設計的核心是 CryptoStream。 任何實 CryptoStream 作的密碼編譯物件都可以與任何實 Stream作 的物件鏈結在一起,因此可以將來自某個對象的數據流輸出饋送至另一個對象的輸入。 中繼結果 (第一個對象的輸出) 不需要個別儲存。

重要

在 .NET 6 和更新版本中,當 或 Stream.ReadAsync 以長度N為 的緩衝區呼叫 時Stream.Read,作業會在至少從數據流讀取 1 個字節時完成,或從 呼叫Read傳回 0 的基礎數據流,表示沒有更多數據可用。 在 .NET 6 之前, Stream.Read 除非 Stream.ReadAsync 從數據流讀取所有 N 位元組,或基礎數據流從呼叫 Read傳回 0,否則不會傳回 。 如果您的程式代碼假設 Read 方法在讀取所有 N 位元組之前都不會傳回,則可能無法讀取所有內容。 如需詳細資訊,請參閱 數據流中的部分和零位元組讀取

呼叫 方法完成之後Clear,您應該一律明確地關閉物件CryptoStream。 這麼做會排清基礎數據流,並讓對象處理 CryptoStream 所有剩餘的數據區塊。 不過,如果在呼叫 Close 方法之前發生例外狀況, CryptoStream 可能無法關閉物件。 若要確保Close一律呼叫 方法,請將您的呼叫Clear放在 語句的 try/catch 區塊內。finally

此型別代表 IDisposable 介面。 當您完成使用型別時,應該藉由呼叫其 Clear 方法來直接或間接處置它,進而呼叫其 IDisposable 實作。 若要直接處置型別,請呼叫其 try/catch 區塊中的 Clear 方法。 若要間接處置它,請使用語言建構函式,例如 using (在 C# 中) 或 Using (在 Visual Basic 中)。

建構函式

CryptoStream(Stream, ICryptoTransform, CryptoStreamMode)

使用目標資料流、要使用的轉換與資料流的模式來初始化新的 CryptoStream 類別。

CryptoStream(Stream, ICryptoTransform, CryptoStreamMode, Boolean)

初始化 CryptoStream 類別的新執行個體。

屬性

CanRead

取得指示目前的 CryptoStream 是否可讀取的值。

CanSeek

取得指示您是否可以在目前的 CryptoStream 內搜尋的值。

CanTimeout

取得值,該值判斷目前的資料流是否可以逾時。

(繼承來源 Stream)
CanWrite

取得指示目前的 CryptoStream 是否可寫入的值。

HasFlushedFinalBlock

取得值,這個值表示最後的緩衝區區塊是否已寫入基礎資料流。

Length

取得資料流的位元組長度。

Position

取得或設定在目前資料流中的位置。

ReadTimeout

取得或設定值 (以毫秒為單位),該值決定資料流在逾時前將嘗試讀取多長時間。

(繼承來源 Stream)
WriteTimeout

取得或設定毫秒值,該值決定在逾時前資料流將嘗試寫入多長時間。

(繼承來源 Stream)

方法

BeginRead(Byte[], Int32, Int32, AsyncCallback, Object)

開始非同步的讀取作業。 (請考慮用 ReadAsync 替代。)

BeginRead(Byte[], Int32, Int32, AsyncCallback, Object)

開始非同步的讀取作業。 (請考慮用 ReadAsync(Byte[], Int32, Int32) 替代。)

(繼承來源 Stream)
BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object)

開始非同步的寫入作業。 (請考慮用 WriteAsync 替代。)

BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object)

開始非同步的寫入作業。 (請考慮用 WriteAsync(Byte[], Int32, Int32) 替代。)

(繼承來源 Stream)
Clear()

釋放 CryptoStream 所使用的所有資源。

Close()

關閉目前資料流和釋放與目前資料流相關聯的任何資源 (例如通訊端和檔案控制代碼)。

Close()

關閉目前資料流和釋放與目前資料流相關聯的任何資源 (例如通訊端和檔案控制代碼)。 請確定正確地處置資料流,而非呼叫這個方法。

(繼承來源 Stream)
CopyTo(Stream)

從目前資料流讀取位元組,並將其寫入另一個資料流中。 這兩個數據流位置會依複製的位元元組數目進階。

(繼承來源 Stream)
CopyTo(Stream, Int32)

從基礎數據流讀取位元組、套用相關的密碼編譯轉換,並將結果寫入目的地數據流。

CopyTo(Stream, Int32)

使用指定的緩衝區大小,從目前資料流讀取所有位元組,並將其寫入另一個資料流中。 這兩個數據流位置會依複製的位元元組數目進階。

(繼承來源 Stream)
CopyToAsync(Stream)

以非同步的方式從目前資料流讀取所有位元組,並將其寫入另一個資料流中。 這兩個數據流位置會依複製的位元元組數目進階。

(繼承來源 Stream)
CopyToAsync(Stream, CancellationToken)

使用指定的取消權杖,以非同步的方式從目前資料流讀取位元組,並將其寫入另一個資料流。 這兩個數據流位置會依複製的位元元組數目進階。

(繼承來源 Stream)
CopyToAsync(Stream, Int32)

使用指定的緩衝區大小,以非同步的方式從目前資料流讀取所有位元組,並將其寫入另一個資料流中。 這兩個數據流位置會依複製的位元元組數目進階。

(繼承來源 Stream)
CopyToAsync(Stream, Int32, CancellationToken)

以異步方式從基礎數據流讀取位元組、套用相關的密碼編譯轉換,並將結果寫入目的地數據流。

CopyToAsync(Stream, Int32, CancellationToken)

使用指定的緩衝區大小和取消語彙基元,以非同步的方式從目前資料流讀取位元組,並將其寫入另一個資料流。 這兩個數據流位置會依複製的位元元組數目進階。

(繼承來源 Stream)
CreateObjRef(Type)

建立包含所有相關資訊的物件,這些資訊是產生用來與遠端物件通訊的所需 Proxy。

(繼承來源 MarshalByRefObject)
CreateWaitHandle()
已淘汰.
已淘汰.
已淘汰.

配置 WaitHandle 物件。

(繼承來源 Stream)
Dispose()

釋放 Stream 所使用的所有資源。

(繼承來源 Stream)
Dispose(Boolean)

釋放 CryptoStream 所使用的 Unmanaged 資源,並選擇性地釋放 Managed 資源。

DisposeAsync()

以非同步方式釋放 CryptoStream 使用的不受控資源。

DisposeAsync()

以非同步方式釋放 Stream 使用的不受控資源。

(繼承來源 Stream)
EndRead(IAsyncResult)

等候暫止的非同步讀取完成。 (請考慮用 ReadAsync 替代。)

EndRead(IAsyncResult)

等候暫止的非同步讀取完成。 (請考慮用 ReadAsync(Byte[], Int32, Int32) 替代。)

(繼承來源 Stream)
EndWrite(IAsyncResult)

結束非同步的寫入作業。 (請考慮用 WriteAsync 替代。)

EndWrite(IAsyncResult)

結束非同步的寫入作業。 (請考慮用 WriteAsync(Byte[], Int32, Int32) 替代。)

(繼承來源 Stream)
Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
Finalize()

允許物件在記憶體回收進行回收之前,嘗試釋放資源並執行其他清除作業。

Flush()

清除目前資料流的所有緩衝區,並且造成所有緩衝資料都寫入基礎裝置。

FlushAsync()

以非同步的方式清除這個資料流的所有緩衝區,並造成所有緩衝資料都寫入基礎裝置。

(繼承來源 Stream)
FlushAsync(CancellationToken)

以非同步的方式清除目前資料流的所有緩衝區,造成所有緩衝資料都寫入基礎裝置,並且監視取消要求。

FlushAsync(CancellationToken)

以非同步的方式清除這個資料流的所有緩衝區,造成所有緩衝資料都寫入基礎裝置,並且監視取消要求。

(繼承來源 Stream)
FlushFinalBlock()

以緩衝區的目前狀態更新基礎資料來源或存放庫,並接著清除緩衝區。

FlushFinalBlockAsync(CancellationToken)

以緩衝區的目前狀態非同步更新基礎資料來源或存放庫,並接著清除緩衝區。

GetHashCode()

做為預設雜湊函式。

(繼承來源 Object)
GetLifetimeService()
已淘汰.

擷取控制這個執行個體存留期 (Lifetime) 原則的目前存留期服務物件。

(繼承來源 MarshalByRefObject)
GetType()

取得目前執行個體的 Type

(繼承來源 Object)
InitializeLifetimeService()
已淘汰.

取得存留期服務物件,以控制這個執行個體的存留期原則。

(繼承來源 MarshalByRefObject)
MemberwiseClone()

建立目前 Object 的淺層複製。

(繼承來源 Object)
MemberwiseClone(Boolean)

建立目前 MarshalByRefObject 物件的淺層複本。

(繼承來源 MarshalByRefObject)
ObjectInvariant()
已淘汰.

提供 Contract 的支援。

(繼承來源 Stream)
Read(Byte[], Int32, Int32)

從目前的資料流讀取位元組序列,並依讀取的位元組數將資料流中的位置往前移。

Read(Span<Byte>)

當在衍生類別中覆寫時,自目前資料流讀取一連串的位元組,並依所讀取的位元組數目進階資料流中的位置。

(繼承來源 Stream)
ReadAsync(Byte[], Int32, Int32)

以非同步的方式從目前的資料流讀取位元組序列,並依讀取的位元組數將資料流中的位置往前移。

(繼承來源 Stream)
ReadAsync(Byte[], Int32, Int32, CancellationToken)

自目前資料流非同步讀取一連串的位元組、依所讀取的位元組數目進階資料流中的位置,以及監視取消要求。

ReadAsync(Byte[], Int32, Int32, CancellationToken)

以非同步的方式從目前資料流讀取一連串的位元組、依所讀取的位元組數目進階資料流中的位置,以及監視取消要求。

(繼承來源 Stream)
ReadAsync(Memory<Byte>, CancellationToken)

以非同步的方式從目前資料流讀取一連串的位元組、依所讀取的位元組數目進階資料流中的位置,以及監視取消要求。

ReadAsync(Memory<Byte>, CancellationToken)

以非同步的方式從目前資料流讀取一連串的位元組、依所讀取的位元組數目進階資料流中的位置,以及監視取消要求。

(繼承來源 Stream)
ReadAtLeast(Span<Byte>, Int32, Boolean)

至少會從目前的數據流讀取位元組數目,並將數據流中的位置前移為讀取的位元組數目。

(繼承來源 Stream)
ReadAtLeastAsync(Memory<Byte>, Int32, Boolean, CancellationToken)

以異步方式從目前數據流讀取至少位元組數目、依讀取的位元組數目將數據流中的位置往前移,並監視取消要求。

(繼承來源 Stream)
ReadByte()

從資料流讀取一個位元組,並將資料流的位置推進一個位元組;如果在資料流末端,則傳回 -1。

ReadByte()

從資料流讀取一個位元組,並將資料流的位置推進一個位元組;如果在資料流末端,則傳回 -1。

(繼承來源 Stream)
ReadExactly(Byte[], Int32, Int32)

count從目前的數據流讀取位元組數目,並將數據流中的位置往前移。

(繼承來源 Stream)
ReadExactly(Span<Byte>)

從目前的數據流讀取位元組,並將數據流內的位置往前移,直到 buffer 填滿為止。

(繼承來源 Stream)
ReadExactlyAsync(Byte[], Int32, Int32, CancellationToken)

以異步方式從目前數據流讀取 count 位元組數目、將數據流內的位置往前移,以及監視取消要求。

(繼承來源 Stream)
ReadExactlyAsync(Memory<Byte>, CancellationToken)

以異步方式從目前的數據流讀取位元組、將數據流內的位置往前移,直到 buffer 填滿為止,並監視取消要求。

(繼承來源 Stream)
Seek(Int64, SeekOrigin)

設定目前資料流位置。

SetLength(Int64)

設定目前資料流的長度。

ToString()

傳回代表目前物件的字串。

(繼承來源 Object)
Write(Byte[], Int32, Int32)

寫入一位元組序列至目前的 CryptoStream,並依所寫入的位元組數目進階這個資料流裡的目前位置。

Write(ReadOnlySpan<Byte>)

在衍生類別中覆寫時,將一連串的位元組寫入目前的資料流,並且由這個資料流中目前的位置前移寫入的位元組數目。

(繼承來源 Stream)
WriteAsync(Byte[], Int32, Int32)

以非同步的方式將位元組序列寫入至目前的資料流,並依寫入的位元組數將資料流中目前的位置往前移。

(繼承來源 Stream)
WriteAsync(Byte[], Int32, Int32, CancellationToken)

以非同步的方式將一連串的位元組寫入至目前的資料流,由這個資料流中目前的位置前移寫入的位元組數目,並且監視取消要求。

WriteAsync(Byte[], Int32, Int32, CancellationToken)

以非同步的方式將一連串的位元組寫入目前的資料流,由這個資料流中目前的位置前移寫入的位元組數目,並且監視取消要求。

(繼承來源 Stream)
WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

以非同步的方式將一連串的位元組寫入目前的資料流,由這個資料流中目前的位置前移寫入的位元組數目,並且監視取消要求。

WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

以非同步的方式將一連串的位元組寫入目前的資料流,由這個資料流中目前的位置前移寫入的位元組數目,並且監視取消要求。

(繼承來源 Stream)
WriteByte(Byte)

寫入一個位元組至資料流的目前位置,並將資料流位置推進一個位元組。

WriteByte(Byte)

寫入一個位元組至資料流的目前位置,並將資料流位置推進一個位元組。

(繼承來源 Stream)

明確介面實作

IDisposable.Dispose()

此 API 支援此產品基礎結構,但無法直接用於程式碼之中。

CryptoStream 類別的目前執行個體所使用的資源釋出。

擴充方法

ConfigureAwait(IAsyncDisposable, Boolean)

設定如何執行從非同步可處置項目傳回的工作 await。

適用於

另請參閱