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对象后,应始终通过Clear调用方法来显式关闭该对象。You 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对方法的调用置于catch语句的finallytry /内。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)

创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。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 占用的非托管资源,还可以另外再释放托管资源。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()

检索控制此实例的生存期策略的当前生存期服务对象。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 的浅表副本。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.

适用于

另请参阅