Condividi tramite


CryptoStream Constructor

Microsoft Silverlight will reach end of support after October 2021. Learn more.

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)

Syntax

'Declaration
Public Sub New ( _
    stream As Stream, _
    transform As ICryptoTransform, _
    mode As CryptoStreamMode _
)
public CryptoStream(
    Stream stream,
    ICryptoTransform transform,
    CryptoStreamMode mode
)

Parameters

  • stream
    Type: System.IO.Stream
    The stream on which to perform the cryptographic transformation.

Exceptions

Exception Condition
ArgumentException

stream is not readable.

ArgumentException

stream is not writable.

ArgumentException

stream is invalid.

Remarks

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.

Examples

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.

Using aes = New System.Security.Cryptography.AesManaged()
    Dim deriveBytes As New Rfc2898DeriveBytes(passwordBox.Password, Encoding.UTF8.GetBytes(PasswordSalt))
    aes.Key = deriveBytes.GetBytes(128 / 8)
    If Integer.MaxValue = Int64.MaxValue Then intSize = 8
    isoStoreStream.Write(BitConverter.GetBytes(aes.IV.Length), 0, intSize)
    isoStoreStream.Write(aes.IV, 0, aes.IV.Length)
    Using cs As New CryptoStream(isoStoreStream, aes.CreateEncryptor(), CryptoStreamMode.Write)
        Dim rawPlaintext As Byte() = Encoding.Unicode.GetBytes(inputBox.Text)
        cs.Write(rawPlaintext, 0, rawPlaintext.Length)
        cs.FlushFinalBlock()
    End Using
End Using
using (Aes aes = new AesManaged())
{
    Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(passwordBox.Password, Encoding.UTF8.GetBytes(PasswordSalt));
    aes.Key = deriveBytes.GetBytes(128 / 8);
    isoStoreStream.Write(BitConverter.GetBytes(aes.IV.Length), 0, sizeof(int));
    isoStoreStream.Write(aes.IV, 0, aes.IV.Length);

    using (CryptoStream cs = new CryptoStream(isoStoreStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
    {
        byte[] rawPlaintext = Encoding.Unicode.GetBytes(inputBox.Text);
        cs.Write(rawPlaintext, 0, rawPlaintext.Length);
        cs.FlushFinalBlock();
    }
}

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.