CryptoStream Class
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Defines a stream that links data streams to cryptographic transformations.
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
- Inheritance
- Inheritance
- Attributes
- Implements
The following example demonstrates how to use a CryptoStream to encrypt a string. This method uses the Aes class with the specified Key and initialization vector (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
The common language runtime uses a stream-oriented design for cryptography. The core of this design is CryptoStream. 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.
Important
In .NET 6 and later versions, when Stream.Read
or Stream.ReadAsync
is called with a buffer of length N
, the operation completes when either at least 1 byte has been read from the stream, or the underlying stream that it wraps returns 0 from a call to Read
, indicating no more data is available. Prior to .NET 6, Stream.Read
and Stream.ReadAsync
did not return until all N
bytes had been read from the stream or the underlying stream returned 0 from a call to Read
. If your code assumes the Read
methods won't return until all N
bytes have been read, it could fail to read all the content. For more information, see Partial and zero-byte reads in streams.
You should always explicitly close your CryptoStream object after you're finished using it by calling the Clear method. Doing so flushes the underlying stream and causes all remaining blocks of data to be processed by the CryptoStream object. However, if an exception occurs before you call the Close method, the CryptoStream object might not be closed. 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.
This type implements the IDisposable interface. When you've 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. To dispose of the type directly, call its Clear method in a try
/catch
block. To dispose of it indirectly, use a language construct such as using
(in C#) or Using
(in Visual Basic).
Crypto |
Initializes a new instance of the CryptoStream class. |
Crypto |
Initializes a new instance of the CryptoStream class with a target data stream, the transformation to use, and the mode of the stream. |
Can |
Gets a value indicating whether the current CryptoStream is readable. |
Can |
Gets a value indicating whether you can seek within the current CryptoStream. |
Can |
Gets a value that determines whether the current stream can time out. (Inherited from Stream) |
Can |
Gets a value indicating whether the current CryptoStream is writable. |
Has |
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. |
Read |
Gets or sets a value, in milliseconds, that determines how long the stream will attempt to read before timing out. (Inherited from Stream) |
Write |
Gets or sets a value, in milliseconds, that determines how long the stream will attempt to write before timing out. (Inherited from Stream) |
Begin |
Begins an asynchronous read operation. (Consider using ReadAsync instead.) |
Begin |
Begins an asynchronous read operation. (Consider using ReadAsync(Byte[], Int32, Int32) instead.) (Inherited from Stream) |
Begin |
Begins an asynchronous write operation. (Consider using WriteAsync instead.) |
Begin |
Begins an asynchronous write operation. (Consider using WriteAsync(Byte[], Int32, Int32) instead.) (Inherited from Stream) |
Clear() |
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. |
Close() |
Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream. Instead of calling this method, ensure that the stream is properly disposed. (Inherited from Stream) |
Copy |
Reads the bytes from the underlying stream, applies the relevant cryptographic transforms, and writes the result to the destination stream. |
Copy |
Reads the bytes from the current stream and writes them to another stream, using a specified buffer size. Both streams positions are advanced by the number of bytes copied. (Inherited from Stream) |
Copy |
Reads the bytes from the current stream and writes them to another stream. Both streams positions are advanced by the number of bytes copied. (Inherited from Stream) |
Copy |
Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified cancellation token. Both streams positions are advanced by the number of bytes copied. (Inherited from Stream) |
Copy |
Asynchronously reads the bytes from the underlying stream, applies the relevant cryptographic transforms, and writes the result to the destination stream. |
Copy |
Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size and cancellation token. Both streams positions are advanced by the number of bytes copied. (Inherited from Stream) |
Copy |
Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size. Both streams positions are advanced by the number of bytes copied. (Inherited from Stream) |
Copy |
Asynchronously reads the bytes from the current stream and writes them to another stream. Both streams positions are advanced by the number of bytes copied. (Inherited from Stream) |
Create |
Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject) |
Create |
Obsolete.
Obsolete.
Obsolete.
Allocates a WaitHandle object. (Inherited from Stream) |
Dispose() |
Releases all resources used by the Stream. (Inherited from Stream) |
Dispose(Boolean) |
Releases the unmanaged resources used by the CryptoStream and optionally releases the managed resources. |
Dispose |
Asynchronously releases the unmanaged resources used by the CryptoStream. |
Dispose |
Asynchronously releases the unmanaged resources used by the Stream. (Inherited from Stream) |
End |
Waits for the pending asynchronous read to complete. (Consider using ReadAsync instead.) |
End |
Waits for the pending asynchronous read to complete. (Consider using ReadAsync(Byte[], Int32, Int32) instead.) (Inherited from Stream) |
End |
Ends an asynchronous write operation. (Consider using WriteAsync instead.) |
End |
Ends an asynchronous write operation. (Consider using WriteAsync(Byte[], Int32, Int32) instead.) (Inherited from Stream) |
Equals(Object) |
Determines whether the specified object is equal to the current object. (Inherited from 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. |
Flush |
Asynchronously clears all buffers for this stream and causes any buffered data to be written to the underlying device. (Inherited from Stream) |
Flush |
Clears all buffers for the current stream asynchronously, causes any buffered data to be written to the underlying device, and monitors cancellation requests. |
Flush |
Asynchronously clears all buffers for this stream, causes any buffered data to be written to the underlying device, and monitors cancellation requests. (Inherited from Stream) |
Flush |
Updates the underlying data source or repository with the current state of the buffer, then clears the buffer. |
Flush |
Asynchronously updates the underlying data source or repository with the current state of the buffer, then clears the buffer. |
Get |
Serves as the default hash function. (Inherited from Object) |
Get |
Obsolete.
Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject) |
Get |
Gets the Type of the current instance. (Inherited from Object) |
Initialize |
Obsolete.
Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject) |
Memberwise |
Creates a shallow copy of the current Object. (Inherited from Object) |
Memberwise |
Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject) |
Object |
Obsolete.
Provides support for a Contract. (Inherited from 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. (Inherited from Stream) |
Read |
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. |
Read |
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. (Inherited from Stream) |
Read |
Asynchronously reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. (Inherited from Stream) |
Read |
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. |
Read |
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. (Inherited from Stream) |
Read |
Reads at least a minimum number of bytes from the current stream and advances the position within the stream by the number of bytes read. (Inherited from Stream) |
Read |
Asynchronously reads at least a minimum number of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests. (Inherited from Stream) |
Read |
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. |
Read |
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. (Inherited from Stream) |
Read |
Reads |
Read |
Reads bytes from the current stream and advances the position within the stream until the |
Read |
Asynchronously reads |
Read |
Asynchronously reads bytes from the current stream, advances the position within the stream until the |
Seek(Int64, Seek |
Sets the position within the current stream. |
Set |
Sets the length of the current stream. |
To |
Returns a string that represents the current object. (Inherited from Object) |
Write(Byte[], Int32, Int32) |
Writes a sequence of bytes to the current CryptoStream and advances the current position within the stream by the number of bytes written. |
Write(Read |
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. (Inherited from Stream) |
Write |
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. |
Write |
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. (Inherited from Stream) |
Write |
Asynchronously writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. (Inherited from Stream) |
Write |
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. |
Write |
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. (Inherited from Stream) |
Write |
Writes a byte to the current position in the stream and advances the position within the stream by one byte. |
Write |
Writes a byte to the current position in the stream and advances the position within the stream by one byte. (Inherited from Stream) |
IDisposable. |
This API supports the product infrastructure and is not intended to be used directly from your code. Releases the resources used by the current instance of the CryptoStream class. |
Copy |
Asynchronously reads the bytes from the Stream and writes them to the specified PipeWriter, using a cancellation token. |
Configure |
Configures how awaits on the tasks returned from an async disposable will be performed. |
Product | Versions |
---|---|
.NET | Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9 |
.NET Framework | 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1 |
.NET Standard | 1.3, 1.4, 1.6, 2.0, 2.1 |
.NET feedback
.NET is an open source project. Select a link to provide feedback: