CryptoStream 類別

定義

定義連結資料流與密碼編譯轉換的資料流。Defines a stream that links data streams to cryptographic transformations.

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

範例

下列範例示範如何使用CryptoStream來加密字串。The following example demonstrates how to use a CryptoStream to encrypt a string. 這個方法會RijndaelManaged使用具有指定Key和初始化向量(IV)的類別。This method uses RijndaelManaged class with the specified Key and initialization vector (IV).

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

namespace RijndaelManaged_Example
{
    class RijndaelExample
    {
        public static void Main()
        {
            try
            {

                string original = "Here is some data to encrypt!";

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

                    // Decrypt the bytes to a string.
                    string roundtrip = DecryptStringFromBytes(encrypted, myRijndael.Key, myRijndael.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("plainText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("IV");
            byte[] encrypted;
            // Create an Rijndael object
            // with the specified key and IV.
            using (Rijndael rijAlg = Rijndael.Create())
            {
                rijAlg.Key = Key;
                rijAlg.IV = IV;

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

                // Create the streams used for encryption.
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(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("cipherText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("IV");

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

            // Create an Rijndael object
            // with the specified key and IV.
            using (Rijndael rijAlg = Rijndael.Create())
            {
                rijAlg.Key = Key;
                rijAlg.IV = IV;

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

                // Create the streams used for decryption.
                using (MemoryStream msDecrypt = new MemoryStream(cipherText))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(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 RijndaelExample

    Public Shared Sub Main()
        Try

            Dim original As String = "Here is some data to encrypt!"

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

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

                ' Decrypt the bytes to a string.
                Dim roundtrip As String = DecryptStringFromBytes(encrypted, myRijndael.Key, myRijndael.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("plainText")
        End If
        If Key Is Nothing OrElse Key.Length <= 0 Then
            Throw New ArgumentNullException("Key")
        End If
        If IV Is Nothing OrElse IV.Length <= 0 Then
            Throw New ArgumentNullException("IV")
        End If
        Dim encrypted() As Byte
        ' Create an Rijndael object
        ' with the specified key and IV.
        Using rijAlg = Rijndael.Create()

            rijAlg.Key = Key
            rijAlg.IV = IV

            ' Create an encryptor to perform the stream transform.
            Dim encryptor As ICryptoTransform = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.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("cipherText")
        End If
        If Key Is Nothing OrElse Key.Length <= 0 Then
            Throw New ArgumentNullException("Key")
        End If
        If IV Is Nothing OrElse IV.Length <= 0 Then
            Throw New ArgumentNullException("IV")
        End If
        ' Declare the string used to hold
        ' the decrypted text.
        Dim plaintext As String = Nothing

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

            ' Create a decryptor to perform the stream transform.
            Dim decryptor As ICryptoTransform = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.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

備註

通用語言執行時間會使用串流導向設計來進行密碼編譯。The common language runtime uses a stream-oriented design for cryptography. 這項設計的核心是CryptoStreamThe core of this design is CryptoStream. 任何執行CryptoStream的密碼編譯物件都可以與任何執行Stream的物件連結在一起,因此來自一個物件的資料流程輸出可以送到另一個物件的輸入。Any cryptographic objects that implement CryptoStream can be chained together with any objects that implement Stream, so the streamed output from one object can be fed into the input of another object. 中繼結果(第一個物件的輸出)不需要另外儲存。The intermediate result (the output from the first object) does not need to be stored separately.

重要

此型別代表 IDisposable 介面。This type implements the IDisposable interface. 當您完成使用型別時,您應該藉由呼叫其Clear方法來直接或間接處置它,這會接著呼叫其IDisposable實作為。When you have finished using the type, you should dispose of it either directly or indirectly by calling its Clear method, which in turn calls its IDisposable implementation. 若要直接處置型別,請呼叫其 try/catch 區塊中的 Clear 方法。To dispose of the type directly, call its Clear method in a try/catch block. 若要間接處置它,請使用語言建構函式,例如 using (在 C# 中) 或 Using (在 Visual Basic 中)。To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). 如需詳細資訊,請參閱 IDisposable 介面文章中的<使用實作 IDisposable 的物件>一節。For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface topic.

呼叫方法之後,您應該CryptoStream一律明確地關閉物件。 ClearYou should always explicitly close your CryptoStream object after you are done using it by calling the Clear method. 這麼做會排清基礎資料流程,並讓CryptoStream物件處理所有剩餘的資料區塊。Doing so flushes the underlying stream and causes all remaining blocks of data to be processed by the CryptoStream object. 不過,如果在呼叫Close方法之前發生例外狀況,則CryptoStream可能不會關閉物件。However, if an exception occurs before you call the Close method, the CryptoStream object might not be closed. 若要確保一律Close會呼叫方法,請將您對Clear方法的呼叫放在finally catch語句區塊try /內。To ensure that the Close method always gets called, place your call to the Clear method within the finally block of a try/catch statement.

建構函式

CryptoStream(Stream, ICryptoTransform, CryptoStreamMode)

使用目標資料流、要使用的轉換和資料流模式,來初始化 CryptoStream 類別的新執行個體。Initializes a new instance of the CryptoStream class with a target data stream, the transformation to use, and the mode of the stream.

CryptoStream(Stream, ICryptoTransform, CryptoStreamMode, Boolean)

初始化 CryptoStream 類別的新執行個體。Initializes a new instance of the CryptoStream class.

屬性

CanRead

取得值,指出目前的 CryptoStream 是否可讀取。Gets a value indicating whether the current CryptoStream is readable.

CanSeek

取得值,指出您是否可以在目前的 CryptoStream 中搜尋。Gets a value indicating whether you can seek within the current CryptoStream.

CanTimeout

取得值,該值判斷目前的資料流是否可以逾時。Gets a value that determines whether the current stream can time out.

(繼承來源 Stream)
CanWrite

取得值,指出目前的 CryptoStream 是否可寫入。Gets a value indicating whether the current CryptoStream is writable.

HasFlushedFinalBlock

取得值,這個值表示最後的緩衝區區塊是否已寫入基礎資料流。Gets a value indicating whether the final buffer block has been written to the underlying stream.

Length

取得資料流的位元組長度。Gets the length in bytes of the stream.

Position

取得或設定在目前資料流中的位置。Gets or sets the position within the current stream.

ReadTimeout

取得或設定值 (以毫秒為單位),這個值決定在逾時前資料流將嘗試讀取多長時間。Gets or sets a value, in milliseconds, that determines how long the stream will attempt to read before timing out.

(繼承來源 Stream)
WriteTimeout

取得或設定值 (以毫秒為單位),這個值決定在逾時前資料流將嘗試寫入多長時間。Gets or sets a value, in milliseconds, that determines how long the stream will attempt to write before timing out.

(繼承來源 Stream)

方法

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

開始非同步的讀取作業。Begins an asynchronous read operation. (請考慮用 ReadAsync 替代。)(Consider using ReadAsync instead.)

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

開始非同步的寫入作業。Begins an asynchronous write operation. (請考慮用 WriteAsync 替代。)(Consider using WriteAsync instead.)

Clear()

釋放 CryptoStream 所使用的所有資源。Releases all resources used by the CryptoStream.

Close()

關閉目前資料流和釋放與目前資料流相關聯的任何資源 (例如通訊端和檔案控制代碼)。Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream.

CopyTo(Stream)

從目前資料流讀取位元組,並將其寫入另一個資料流中。Reads the bytes from the current stream and writes them to another stream.

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

使用指定的緩衝區大小,從目前資料流讀取所有位元組,並將其寫入另一個資料流中。Reads the bytes from the current stream and writes them to another stream, using a specified buffer size.

(繼承來源 Stream)
CopyToAsync(Stream)

以非同步的方式從目前資料流讀取所有位元組,並將其寫入另一個資料流中。Asynchronously reads the bytes from the current stream and writes them to another stream.

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

使用指定的取消權杖,以非同步的方式從目前資料流讀取位元組,並將其寫入另一個資料流。Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified cancellation token.

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

使用指定的緩衝區大小,以非同步的方式從目前資料流讀取所有位元組,並將其寫入另一個資料流中。Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size.

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

使用指定的緩衝區大小和取消語彙基元,以非同步的方式從目前資料流讀取位元組,並將其寫入另一個資料流。Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size and cancellation token.

(繼承來源 Stream)
CreateObjRef(Type)

建立包含所有相關資訊的物件,這些資訊是產生用來與遠端物件通訊的所需 Proxy。Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(繼承來源 MarshalByRefObject)
CreateWaitHandle()

配置 WaitHandle 物件。Allocates a WaitHandle object.

(繼承來源 Stream)
Dispose()

釋放 Stream 所使用的所有資源。Releases all resources used by the Stream.

(繼承來源 Stream)
Dispose(Boolean)

釋放 CryptoStream 所使用的 Unmanaged 資源,並選擇性地釋放 Managed 資源。Releases the unmanaged resources used by the CryptoStream and optionally releases the managed resources.

DisposeAsync()

以非同步方式釋放 CryptoStream 使用的不受控資源。Asynchronously releases the unmanaged resources used by the CryptoStream.

EndRead(IAsyncResult)

等候暫止的非同步讀取完成。Waits for the pending asynchronous read to complete. (請考慮用 ReadAsync 替代。)(Consider using ReadAsync instead.)

EndWrite(IAsyncResult)

結束非同步的寫入作業。Ends an asynchronous write operation. (請考慮用 WriteAsync 替代。)(Consider using WriteAsync instead.)

Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(繼承來源 Object)
Finalize()

允許物件在記憶體回收進行回收之前,嘗試釋放資源並執行其他清除作業。Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.

Flush()

清除目前資料流的所有緩衝區,並且造成任何緩衝資料都寫入基礎裝置。Clears all buffers for the current stream and causes any buffered data to be written to the underlying device.

FlushAsync()

以非同步的方式清除這個資料流的所有緩衝區,並造成所有緩衝資料都寫入基礎裝置。Asynchronously clears all buffers for this stream and causes any buffered data to be written to the underlying device.

(繼承來源 Stream)
FlushAsync(CancellationToken)

以非同步的方式清除目前資料流的所有緩衝區,造成任何緩衝資料都寫入基礎裝置,並且監視取消要求。Clears all buffers for the current stream asynchronously, causes any buffered data to be written to the underlying device, and monitors cancellation requests.

FlushFinalBlock()

以緩衝區的目前狀態更新基礎資料來源或存放庫,並接著清除緩衝區。Updates the underlying data source or repository with the current state of the buffer, then clears the buffer.

GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(繼承來源 Object)
GetLifetimeService()

擷取控制這個執行個體存留期 (Lifetime) 原則的目前存留期服務物件。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(繼承來源 MarshalByRefObject)
GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(繼承來源 Object)
InitializeLifetimeService()

取得存留期服務物件,以控制這個執行個體的存留期原則。Obtains a lifetime service object to control the lifetime policy for this instance.

(繼承來源 MarshalByRefObject)
MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(繼承來源 Object)
MemberwiseClone(Boolean)

建立目前 MarshalByRefObject 物件的淺層複本。Creates a shallow copy of the current MarshalByRefObject object.

(繼承來源 MarshalByRefObject)
ObjectInvariant()

提供 Contract 的支援。Provides support for a Contract.

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

從目前的資料流讀取位元組序列,並依讀取的位元組數將資料流中的位置往前移。Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.

Read(Span<Byte>)

當在衍生類別中覆寫時,自目前資料流讀取一連串的位元組,並依所讀取的位元組數目進階資料流中的位置。When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.

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

以非同步的方式從目前的資料流讀取位元組序列,並依讀取的位元組數將資料流中的位置往前移。Asynchronously reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.

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

自目前資料流非同步讀取一連串的位元組、依所讀取的位元組數目進階資料流中的位置,以及監視取消要求。Reads a sequence of bytes from the current stream asynchronously, advances the position within the stream by the number of bytes read, and monitors cancellation requests.

ReadAsync(Memory<Byte>, CancellationToken)

以非同步的方式從目前資料流讀取一連串的位元組、依所讀取的位元組數目進階資料流中的位置,以及監視取消要求。Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests.

(繼承來源 Stream)
ReadByte()

從資料流讀取一個位元組,並將資料流的位置推進一個位元組;如果在資料流末端,則傳回 -1。Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream.

Seek(Int64, SeekOrigin)

設定目前資料流位置。Sets the position within the current stream.

SetLength(Int64)

設定目前資料流的長度。Sets the length of the current stream.

ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

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

寫入一位元組序列至目前的 CryptoStream,並依所寫入的位元組數目進階這個資料流裡的目前位置。Writes a sequence of bytes to the current CryptoStream and advances the current position within the stream by the number of bytes written.

Write(ReadOnlySpan<Byte>)

在衍生類別中覆寫時,將一連串的位元組寫入目前的資料流,並且由這個資料流中目前的位置前移寫入的位元組數目。When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.

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

以非同步的方式將位元組序列寫入至目前的資料流,並依寫入的位元組數將資料流中目前的位置往前移。Asynchronously writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.

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

以非同步的方式將一連串的位元組寫入至目前的資料流,由這個資料流中目前的位置前移寫入的位元組數目,並且監視取消要求。Writes a sequence of bytes to the current stream asynchronously, advances the current position within the stream by the number of bytes written, and monitors cancellation requests.

WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

以非同步的方式將一連串的位元組寫入目前的資料流,由這個資料流中目前的位置前移寫入的位元組數目,並且監視取消要求。Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests.

(繼承來源 Stream)
WriteByte(Byte)

寫入一個位元組至資料流的目前位置,並將資料流位置推進一個位元組。Writes a byte to the current position in the stream and advances the position within the stream by one byte.

明確介面實作

IDisposable.Dispose()

CryptoStream 類別的目前執行個體所使用的資源釋出。Releases the resources used by the current instance of the CryptoStream class.

適用於

另請參閱