CryptoStream Constructor

July 28, 2014

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

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

public CryptoStream(
	Stream stream,
	ICryptoTransform transform,
	CryptoStreamMode mode
)

Parameters

stream
Type: System.IO.Stream
The stream on which to perform the cryptographic transformation.
transform
Type: System.Security.Cryptography.ICryptoTransform
The cryptographic transformation that is to be performed on the stream.
mode
Type: System.Security.Cryptography.CryptoStreamMode
One of the enumeration values that specifies whether to read or write the cryptographic stream.

ExceptionCondition
ArgumentException

stream is not readable.

ArgumentException

stream is not writable.

ArgumentException

stream is invalid.

Any object that derives from Stream can be passed into the stream parameter. Any object that implements ICryptoTransform (such as HashAlgorithm) can be passed into the transform parameter.

The following example demonstrates how to use the CryptoStream constructor when you encrypt an isolated storage file. This code example is part of a larger example provided for the AesManaged class.


static string DecryptStringFromBytes_Aes(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 AesManaged object
    // with the specified key and IV.
    using (AesManaged aesAlg = new AesManaged())
    {
        aesAlg.Key = Key;
        aesAlg.IV = IV;

        // Create a decrytor to perform the stream transform.
        ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.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;

}


Windows Phone OS

Supported in: 8.1, 8.0, 7.1, 7.0

Windows Phone

Show:
© 2014 Microsoft