CryptoStream 类
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
定义将数据流链接到加密转换的流。
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 来加密字符串。 此方法使用 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
注解
公共语言运行时使用面向流的加密设计。 此设计的核心是 CryptoStream。 实现 CryptoStream 的任何加密对象都可以与实现 Stream的任何对象链接在一起,因此一个对象的流输出可以馈送到另一个对象的输入中。 第一个对象 (输出) 的中间结果不需要单独存储。
重要
在 .NET 6 及更高版本中,当 Stream.Read
使用长度N
的缓冲区调用 或 Stream.ReadAsync
时,当至少从流中读取 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) |
创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。 (继承自 MarshalByRefObject) |
CreateWaitHandle() |
已过时.
已过时.
已过时.
分配 WaitHandle 对象。 (继承自 Stream) |
Dispose() |
释放由 Stream 使用的所有资源。 (继承自 Stream) |
Dispose(Boolean) |
释放由 CryptoStream 占用的非托管资源,还可以另外再释放托管资源。 |
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() |
已过时.
检索控制此实例的生存期策略的当前生存期服务对象。 (继承自 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) |
|
ReadExactly(Span<Byte>) |
从当前流中读取字节,并推进流中的位置, |
ReadExactlyAsync(Byte[], Int32, Int32, CancellationToken) |
从当前流异步读取 |
ReadExactlyAsync(Memory<Byte>, CancellationToken) |
从当前流异步读取字节,推进流中的位置,直到 |
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 类的当前实例使用的资源。 |
扩展方法
CopyToAsync(Stream, PipeWriter, CancellationToken) |
使用取消令牌从 Stream 中异步读取字节并将其写入到指定的 PipeWriter。 |
ConfigureAwait(IAsyncDisposable, Boolean) |
配置如何执行从异步可处置项返回的任务的等待。 |
适用于
另请参阅
反馈
https://aka.ms/ContentUserFeedback。
即将发布:在整个 2024 年,我们将逐步淘汰作为内容反馈机制的“GitHub 问题”,并将其取代为新的反馈系统。 有关详细信息,请参阅:提交和查看相关反馈