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 来加密字符串。 此方法使用具有指定 Key 和初始化向量(IV)的 Aes 类。
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 及更高版本中,当使用长度为 N
的缓冲区调用 Stream.Read
或 Stream.ReadAsync
时,该操作将在至少从流中读取 1 个字节时完成,或者它包装的基础流从调用 Read
返回 0,表示没有更多可用数据。 在 .NET 6 之前,在从流读取所有 N
字节或从调用 Read
返回 0 的基础流之前,Stream.Read
和 Stream.ReadAsync
才返回。 如果代码假定 Read
方法在读取所有 N
字节之前不会返回,则可能无法读取所有内容。 有关详细信息,请参阅 流中的部分读取和零字节读取。
使用完 Clear 方法后,应始终显式关闭 CryptoStream 对象。 这样做会刷新基础流,并导致 CryptoStream 对象处理所有剩余的数据块。 但是,如果在调用 Close 方法之前发生异常,则 CryptoStream 对象可能不会关闭。 若要确保始终调用 Close 方法,请将调用置于 try
/catch
语句的 finally
块中 Clear 方法。
此类型实现 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) |
方法
显式接口实现
IDisposable.Dispose() |
此 API 支持产品基础结构,不能在代码中直接使用。 释放 CryptoStream 类的当前实例使用的资源。 |
扩展方法
CopyToAsync(Stream, PipeWriter, CancellationToken) |
使用取消令牌从 Stream 异步读取字节并将其写入指定的 PipeWriter。 |
ConfigureAwait(IAsyncDisposable, Boolean) |
配置如何执行从异步可释放项返回的任务的 await。 |
适用于
另请参阅
- 加密服务
- DeflateStream、GZipStream 和 CryptoStream 中的部分读取和零字节读取