Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

CryptoStream Class

Defines a stream that links data streams to cryptographic transformations.

System.Object
  System.MarshalByRefObject
    System.IO.Stream
      System.Security.Cryptography.CryptoStream

Namespace:  System.Security.Cryptography
Assembly:  mscorlib (in mscorlib.dll)

[ComVisibleAttribute(true)]
public class CryptoStream : Stream, 
	IDisposable

The CryptoStream type exposes the following members.

  NameDescription
Public methodCryptoStreamInitializes a new instance of the CryptoStream class with a target data stream, the transformation to use, and the mode of the stream.
Top

  NameDescription
Public propertyCanReadGets a value indicating whether the current CryptoStream is readable. (Overrides Stream.CanRead.)
Public propertyCanSeekGets a value indicating whether you can seek within the current CryptoStream. (Overrides Stream.CanSeek.)
Public propertyCanTimeoutGets a value that determines whether the current stream can time out. (Inherited from Stream.)
Public propertyCanWriteGets a value indicating whether the current CryptoStream is writable. (Overrides Stream.CanWrite.)
Public propertyHasFlushedFinalBlockGets a value indicating whether the final buffer block has been written to the underlying stream.
Public propertyLengthGets the length in bytes of the stream. (Overrides Stream.Length.)
Public propertyPositionGets or sets the position within the current stream. (Overrides Stream.Position.)
Public propertyReadTimeoutGets or sets a value, in miliseconds, that determines how long the stream will attempt to read before timing out. (Inherited from Stream.)
Public propertyWriteTimeoutGets or sets a value, in miliseconds, that determines how long the stream will attempt to write before timing out. (Inherited from Stream.)
Top

  NameDescription
Public methodBeginReadBegins an asynchronous read operation. (Consider using ReadAsync instead; see the Remarks section.) (Inherited from Stream.)
Public methodBeginWriteBegins an asynchronous write operation. (Consider using WriteAsync instead; see the Remarks section.) (Inherited from Stream.)
Public methodClearReleases all resources used by the CryptoStream.
Public methodCloseCloses 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.)
Public methodCopyTo(Stream)Reads the bytes from the current stream and writes them to another stream. (Inherited from Stream.)
Public methodCopyTo(Stream, Int32)Reads the bytes from the current stream and writes them to another stream, using a specified buffer size. (Inherited from Stream.)
Public methodCopyToAsync(Stream)Asynchronously reads the bytes from the current stream and writes them to another stream. (Inherited from Stream.)
Public methodCopyToAsync(Stream, Int32)Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size. (Inherited from Stream.)
Public methodCopyToAsync(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. (Inherited from Stream.)
Public methodCreateObjRefCreates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
Protected methodCreateWaitHandle Obsolete. Allocates a WaitHandle object. (Inherited from Stream.)
Public methodDispose()Releases all resources used by the Stream. (Inherited from Stream.)
Protected methodDispose(Boolean)Releases the unmanaged resources used by the CryptoStream and optionally releases the managed resources. (Overrides Stream.Dispose(Boolean).)
Public methodEndReadWaits for the pending asynchronous read to complete. (Consider using ReadAsync instead; see the Remarks section.) (Inherited from Stream.)
Public methodEndWriteEnds an asynchronous write operation. (Consider using WriteAsync instead; see the Remarks section.) (Inherited from Stream.)
Public methodEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected methodFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodFlushClears all buffers for the current stream and causes any buffered data to be written to the underlying device. (Overrides Stream.Flush().)
Public methodFlushAsync()Asynchronously clears all buffers for this stream and causes any buffered data to be written to the underlying device. (Inherited from Stream.)
Public methodFlushAsync(CancellationToken)Clears all buffers for the current stream asynchronously, causes any buffered data to be written to the underlying device, and monitors cancellation requests. (Overrides Stream.FlushAsync(CancellationToken).)
Public methodFlushFinalBlockUpdates the underlying data source or repository with the current state of the buffer, then clears the buffer.
Public methodGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodGetLifetimeServiceRetrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodInitializeLifetimeServiceObtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected methodMemberwiseClone()Creates a shallow copy of the current Object. (Inherited from Object.)
Protected methodMemberwiseClone(Boolean)Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.)
Protected methodObjectInvariantInfrastructure. Obsolete. Provides support for a Contract. (Inherited from Stream.)
Public methodReadReads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. (Overrides Stream.Read(Byte[], Int32, Int32).)
Public methodReadAsync(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.)
Public methodReadAsync(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. (Overrides Stream.ReadAsync(Byte[], Int32, Int32, CancellationToken).)
Public methodReadByteReads 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.)
Public methodSeekSets the position within the current stream. (Overrides Stream.Seek(Int64, SeekOrigin).)
Public methodSetLengthSets the length of the current stream. (Overrides Stream.SetLength(Int64).)
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Public methodWriteWrites a sequence of bytes to the current CryptoStream and advances the current position within the stream by the number of bytes written. (Overrides Stream.Write(Byte[], Int32, Int32).)
Public methodWriteAsync(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.)
Public methodWriteAsync(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. (Overrides Stream.WriteAsync(Byte[], Int32, Int32, CancellationToken).)
Public methodWriteByteWrites a byte to the current position in the stream and advances the position within the stream by one byte. (Inherited from Stream.)
Top

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 noteImportant

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.

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.

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("Key");
            byte[] encrypted;
            // Create an Rijndael object 
            // with the specified key and IV. 
            using (Rijndael rijAlg = Rijndael.Create())
            {
                rijAlg.Key = Key;
                rijAlg.IV = IV;

                // Create a decrytor 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("Key");

            // 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 decrytor 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;

        }
    }
}

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone 8, Silverlight 8.1

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Show:
© 2014 Microsoft