ערוך

שתף באמצעות


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

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

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

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

CopyToAsync(Stream, PipeWriter, CancellationToken)

Asynchronously reads the bytes from the Stream and writes them to the specified PipeWriter, using a cancellation token.

ConfigureAwait(IAsyncDisposable, Boolean)

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

Applies to

See also