CryptoStream Class

Definition

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
CryptoStream
Inheritance
Attributes
Implements

Examples

The following example demonstrates how to use a CryptoStream to encrypt a string. 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

Remarks

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

  • This type implements the IDisposable interface. 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. 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). For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface topic.

  • When Stream.Read or Stream.ReadAsync is called with a buffer of length N, the operation completes when either:

    • At least one 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.

    Also, when Stream.Read or Stream.ReadAsync is called with a buffer of length 0, the operation succeeds once a call with a non-zero buffer would succeed.

Prior to .NET 6, Stream.Read and Stream.ReadAsync did not return until N bytes had been read from the stream or the underlying stream returned 0 from a call to Read. If your code assumed they wouldn't return until all N bytes were 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 are done 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.

Constructors

CryptoStream(Stream, ICryptoTransform, CryptoStreamMode)

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)

Initializes a new instance of the CryptoStream class.

Properties

CanRead

Gets a value indicating whether the current CryptoStream is readable.

CanSeek

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.

(Inherited from Stream)
CanWrite

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.

(Inherited from Stream)
WriteTimeout

Gets or sets a value, in milliseconds, that determines how long the stream will attempt to write before timing out.

(Inherited from Stream)

Methods

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

Begins an asynchronous read operation. (Consider using ReadAsync instead.)

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

Begins an asynchronous read operation. (Consider using ReadAsync(Byte[], Int32, Int32) instead.)

(Inherited from Stream)
BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object)

Begins an asynchronous write operation. (Consider using WriteAsync instead.)

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

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)
CopyTo(Stream)

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)
CopyTo(Stream, Int32)

Reads the bytes from the underlying stream, applies the relevant cryptographic transforms, and writes the result to the destination stream.

CopyTo(Stream, Int32)

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)
CopyToAsync(Stream)

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)
CopyToAsync(Stream, CancellationToken)

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)
CopyToAsync(Stream, Int32)

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)
CopyToAsync(Stream, Int32, CancellationToken)

Asynchronously reads the bytes from the underlying stream, applies the relevant cryptographic transforms, and writes the result to the destination 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. Both streams positions are advanced by the number of bytes copied.

(Inherited from Stream)
CreateObjRef(Type)

Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
CreateWaitHandle()
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.

DisposeAsync()

Asynchronously releases the unmanaged resources used by the CryptoStream.

DisposeAsync()

Asynchronously releases the unmanaged resources used by the Stream.

(Inherited from Stream)
EndRead(IAsyncResult)

Waits for the pending asynchronous read to complete. (Consider using ReadAsync instead.)

EndRead(IAsyncResult)

Waits for the pending asynchronous read to complete. (Consider using ReadAsync(Byte[], Int32, Int32) instead.)

(Inherited from Stream)
EndWrite(IAsyncResult)

Ends an asynchronous write operation. (Consider using WriteAsync instead.)

EndWrite(IAsyncResult)

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.

FlushAsync()

Asynchronously clears all buffers for this stream and causes any buffered data to be written to the underlying device.

(Inherited from 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.

FlushAsync(CancellationToken)

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)
FlushFinalBlock()

Updates the underlying data source or repository with the current state of the buffer, then clears the buffer.

FlushFinalBlockAsync(CancellationToken)

Asynchronously 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.

(Inherited from Object)
GetLifetimeService()
Obsolete.

Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetType()

Gets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService()
Obsolete.

Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean)

Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
ObjectInvariant()
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)
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.

(Inherited from 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(Byte[], Int32, Int32, 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.

(Inherited from Stream)
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.

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.

(Inherited from Stream)
ReadAtLeast(Span<Byte>, Int32, Boolean)

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)
ReadAtLeastAsync(Memory<Byte>, Int32, Boolean, CancellationToken)

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)
ReadByte()

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.

ReadByte()

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)
ReadExactly(Byte[], Int32, Int32)

Reads count number of bytes from the current stream and advances the position within the stream.

(Inherited from Stream)
ReadExactly(Span<Byte>)

Reads bytes from the current stream and advances the position within the stream until the buffer is filled.

(Inherited from Stream)
ReadExactlyAsync(Byte[], Int32, Int32, CancellationToken)

Asynchronously reads count number of bytes from the current stream, advances the position within the stream, and monitors cancellation requests.

(Inherited from Stream)
ReadExactlyAsync(Memory<Byte>, CancellationToken)

Asynchronously reads bytes from the current stream, advances the position within the stream until the buffer is filled, and monitors cancellation requests.

(Inherited from 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.

(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(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.

(Inherited from 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.

(Inherited from 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(Byte[], Int32, Int32, 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.

(Inherited from Stream)
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.

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.

(Inherited from Stream)
WriteByte(Byte)

Writes a byte to the current position in the stream and advances the position within the stream by one byte.

WriteByte(Byte)

Writes a byte to the current position in the stream and advances the position within the stream by one byte.

(Inherited from Stream)

Explicit Interface Implementations

IDisposable.Dispose()

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.

Extension Methods

ConfigureAwait(IAsyncDisposable, Boolean)

Configures how awaits on the tasks returned from an async disposable are performed.

Applies to

See also