Movatterモバイル変換


[0]ホーム

URL:


Skip to main contentSkip to in-page navigation

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Download Microsoft EdgeMore info about Internet Explorer and Microsoft Edge
Table of contentsExit editor mode

CryptoStream Class

Definition

Namespace:
System.Security.Cryptography
Assemblies:
netstandard.dll, System.Security.Cryptography.dll
Assemblies:
netstandard.dll, System.Security.Cryptography.Primitives.dll
Assembly:
System.Security.Cryptography.Primitives.dll
Assembly:
mscorlib.dll
Assembly:
netstandard.dll
Source:
CryptoStream.cs
Source:
CryptoStream.cs
Source:
CryptoStream.cs
Source:
CryptoStream.cs

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

Examples

The following example demonstrates how to use aCryptoStream to encrypt a string. This method uses theAes class with the specifiedKey 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.IOImports System.Security.CryptographyClass 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 isCryptoStream. Any cryptographic objects that implementCryptoStream can be chained together with any objects that implementStream, 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, whenStream.Read orStream.ReadAsync is called with a buffer of lengthN, 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 toRead, indicating no more data is available. Prior to .NET 6,Stream.Read andStream.ReadAsync did not return until allN bytes had been read from the stream or the underlying stream returned 0 from a call toRead. If your code assumes theRead methods won't return until allN bytes have been read, it could fail to read all the content. For more information, seePartial and zero-byte reads in streams.

You should always explicitly close yourCryptoStream object after you're finished using it by calling theClear method. Doing so flushes the underlying stream and causes all remaining blocks of data to be processed by theCryptoStream object. However, if an exception occurs before you call theClose method, theCryptoStream object might not be closed. To ensure that theClose method always gets called, place your call to theClear method within thefinally block of atry/catch statement.

This type implements theIDisposable interface. When you've finished using the type, you should dispose of it either directly or indirectly by calling itsClear method, which in turn calls itsIDisposable implementation. To dispose of the type directly, call itsClear method in atry/catch block. To dispose of it indirectly, use a language construct such asusing (in C#) orUsing (in Visual Basic).

Constructors

NameDescription
CryptoStream(Stream, ICryptoTransform, CryptoStreamMode, Boolean)

Initializes a new instance of theCryptoStream class.

CryptoStream(Stream, ICryptoTransform, CryptoStreamMode)

Initializes a new instance of theCryptoStream class with a target data stream, the transformation to use, and the mode of the stream.

Properties

NameDescription
CanRead

Gets a value indicating whether the currentCryptoStream is readable.

CanSeek

Gets a value indicating whether you can seek within the currentCryptoStream.

CanTimeout

Gets a value that determines whether the current stream can time out.

(Inherited fromStream)
CanWrite

Gets a value indicating whether the currentCryptoStream 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 fromStream)
WriteTimeout

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

(Inherited fromStream)

Methods

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

Begins an asynchronous read operation. (Consider usingReadAsync instead.)

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

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

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

Begins an asynchronous write operation. (Consider usingWriteAsync instead.)

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

Begins an asynchronous write operation. (Consider usingWriteAsync(Byte[], Int32, Int32) instead.)

(Inherited fromStream)
Clear()

Releases all resources used by theCryptoStream.

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 fromStream)
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 fromStream)
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 fromStream)
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 fromStream)
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 fromStream)
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 fromStream)
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 fromStream)
CreateObjRef(Type)

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

(Inherited fromMarshalByRefObject)
CreateWaitHandle()
Obsolete.
Obsolete.
Obsolete.

Allocates aWaitHandle object.

(Inherited fromStream)
Dispose()

Releases all resources used by theStream.

(Inherited fromStream)
Dispose(Boolean)

Releases the unmanaged resources used by theCryptoStream and optionally releases the managed resources.

DisposeAsync()

Asynchronously releases the unmanaged resources used by theCryptoStream.

EndRead(IAsyncResult)

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

EndRead(IAsyncResult)

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

(Inherited fromStream)
EndWrite(IAsyncResult)

Ends an asynchronous write operation. (Consider usingWriteAsync instead.)

EndWrite(IAsyncResult)

Ends an asynchronous write operation. (Consider usingWriteAsync(Byte[], Int32, Int32) instead.)

(Inherited fromStream)
Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited fromObject)
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 fromStream)
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.

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 fromObject)
GetLifetimeService()
Obsolete.

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

(Inherited fromMarshalByRefObject)
GetType()

Gets theType of the current instance.

(Inherited fromObject)
InitializeLifetimeService()
Obsolete.

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

(Inherited fromMarshalByRefObject)
MemberwiseClone()

Creates a shallow copy of the currentObject.

(Inherited fromObject)
MemberwiseClone(Boolean)

Creates a shallow copy of the currentMarshalByRefObject object.

(Inherited fromMarshalByRefObject)
ObjectInvariant()
Obsolete.

Provides support for aContract.

(Inherited fromStream)
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 fromStream)
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)

Asynchronously reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.

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

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

(Inherited fromStream)
ReadExactly(Span<Byte>)

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

(Inherited fromStream)
ReadExactlyAsync(Byte[], Int32, Int32, CancellationToken)

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

(Inherited fromStream)
ReadExactlyAsync(Memory<Byte>, CancellationToken)

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

(Inherited fromStream)
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 fromObject)
Write(Byte[], Int32, Int32)

Writes a sequence of bytes to the currentCryptoStream 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 fromStream)
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)

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

Explicit Interface Implementations

NameDescription
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 theCryptoStream class.

Extension Methods

NameDescription
CopyToAsync(Stream, PipeWriter, CancellationToken)

Asynchronously reads the bytes from theStream and writes them to the specifiedPipeWriter, 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

Collaborate with us on GitHub
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, seeour contributor guide.

Feedback

Was this page helpful?

YesNoNo

Need help with this topic?

Want to try using Ask Learn to clarify or guide you through this topic?

Suggest a fix?

In this article

Was this page helpful?

YesNo
NoNeed help with this topic?

Want to try using Ask Learn to clarify or guide you through this topic?

Suggest a fix?