Click to Rate and Give Feedback
MSDN
MSDN Library
.NET Development
.NET Framework
 CreateEncryptor Method (Byte[], Byt...
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
.NET Framework Class Library
RijndaelManaged..::.CreateEncryptor Method (array<Byte>[]()[], array<Byte>[]()[])

Creates a symmetric Rijndael encryptor object with the specified Key and initialization vector (IV).

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

Visual Basic (Declaration)
Public Overrides Function CreateEncryptor ( _
    rgbKey As Byte(), _
    rgbIV As Byte() _
) As ICryptoTransform
Visual Basic (Usage)
Dim instance As RijndaelManaged
Dim rgbKey As Byte()
Dim rgbIV As Byte()
Dim returnValue As ICryptoTransform

returnValue = instance.CreateEncryptor(rgbKey, _
    rgbIV)
C#
public override ICryptoTransform CreateEncryptor(
    byte[] rgbKey,
    byte[] rgbIV
)
Visual C++
public:
virtual ICryptoTransform^ CreateEncryptor(
    array<unsigned char>^ rgbKey, 
    array<unsigned char>^ rgbIV
) override
J#
public ICryptoTransform CreateEncryptor(
    byte[] rgbKey,
    byte[] rgbIV
)
JScript
public override function CreateEncryptor(
    rgbKey : byte[], 
    rgbIV : byte[]
) : ICryptoTransform

Parameters

rgbKey
Type: array< System..::.Byte >[]()[]

The secret key to be used for the symmetric algorithm. The key size must be 126, 128, or 256 bits.

rgbIV
Type: array< System..::.Byte >[]()[]

The IV to be used for the symmetric algorithm.

Return Value

Type: System.Security.Cryptography..::.ICryptoTransform

A symmetric Rijndael encryptor object.

ExceptionCondition
ArgumentNullException

The rgbKey parameter is nullNothingnullptra null reference (Nothing in Visual Basic).

-or-

The rgbIV parameter is nullNothingnullptra null reference (Nothing in Visual Basic).

CryptographicException

The value of the Mode parameter is not ECB, CBC, or CFB.

Use the CreateDecryptor overload with the same signature to decrypt the result of this method.

The rgbkey size must be 126, 128, or 256 bits.

The following code examples demonstrates how to encrypt a message using the CreateEncryptor method.

Visual Basic
Imports System
Imports System.IO
Imports System.Security.Cryptography



Module RijndaelMemoryExample

    Sub Main()
        Try

            Dim original As String = "Here is some data to encrypt!"

            ' Create a new instance of the RijndaelManaged
            ' class.  This generates a new key and initialization 
            ' vector (IV).
            Dim myRijndael As New RijndaelManaged()

            ' Encrypt the string to an array of bytes.
            Dim encrypted As Byte() = encryptStringToBytes_AES(original, myRijndael.Key, myRijndael.IV)

            ' Decrypt the bytes to a string.
            Dim roundtrip As String = decryptStringFromBytes_AES(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 e As Exception
            Console.WriteLine("Error: {0}", e.Message)
        End Try

    End Sub


    Function encryptStringToBytes_AES(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("plainText")
        End If
        If Key Is Nothing OrElse Key.Length <= 0 Then
            Throw New ArgumentNullException("Key")
        End If
        If IV Is Nothing OrElse IV.Length <= 0 Then
            Throw New ArgumentNullException("Key")
        End If
        ' Declare the streams used
        ' to encrypt to an in memory
        ' array of bytes.
        Dim msEncrypt As MemoryStream = Nothing
        Dim csEncrypt As CryptoStream = Nothing
        Dim swEncrypt As StreamWriter = Nothing

        ' Declare the RijndaelManaged object
        ' used to encrypt the data.
        Dim aesAlg As RijndaelManaged = Nothing

        ' Declare the bytes used to hold the
        ' encrypted data.
        Dim encrypted As Byte() = Nothing

        Try
            ' Create a RijndaelManaged object
            ' with the specified key and IV.
            aesAlg = New RijndaelManaged()
            aesAlg.Key = Key
            aesAlg.IV = IV

            ' Create a decrytor to perform the stream transform.
            Dim encryptor As ICryptoTransform = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV)

            ' Create the streams used for encryption.
            msEncrypt = New MemoryStream()
            csEncrypt = New CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)
            swEncrypt = New StreamWriter(csEncrypt)

            'Write all data to the stream.
            swEncrypt.Write(plainText)

        Finally
            ' Clean things up.
            ' Close the streams.
            If Not (swEncrypt Is Nothing) Then
                swEncrypt.Close()
            End If
            If Not (csEncrypt Is Nothing) Then
                csEncrypt.Close()
            End If
            If Not (msEncrypt Is Nothing) Then
                msEncrypt.Close()
            End If
            ' Clear the RijndaelManaged object.
            If Not (aesAlg Is Nothing) Then
                aesAlg.Clear()
            End If
        End Try
        ' Return the encrypted bytes from the memory stream.
        Return msEncrypt.ToArray()

    End Function


    Function decryptStringFromBytes_AES(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("cipherText")
        End If
        If Key Is Nothing OrElse Key.Length <= 0 Then
            Throw New ArgumentNullException("Key")
        End If
        If IV Is Nothing OrElse IV.Length <= 0 Then
            Throw New ArgumentNullException("Key")
        End If
        ' TDeclare the streams used
        ' to decrypt to an in memory
        ' array of bytes.
        Dim msDecrypt As MemoryStream = Nothing
        Dim csDecrypt As CryptoStream = Nothing
        Dim srDecrypt As StreamReader = Nothing

        ' Declare the RijndaelManaged object
        ' used to decrypt the data.
        Dim aesAlg As RijndaelManaged = Nothing

        ' Declare the string used to hold
        ' the decrypted text.
        Dim plaintext As String = Nothing

        Try
            ' Create a RijndaelManaged object
            ' with the specified key and IV.
            aesAlg = New RijndaelManaged()
            aesAlg.Key = Key
            aesAlg.IV = IV

            ' Create a decrytor to perform the stream transform.
            Dim decryptor As ICryptoTransform = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV)

            ' Create the streams used for decryption.
            msDecrypt = New MemoryStream(cipherText)
            csDecrypt = New CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)
            srDecrypt = New StreamReader(csDecrypt)

            ' Read the decrypted bytes from the decrypting stream
            ' and place them in a string.
            plaintext = srDecrypt.ReadToEnd()
        Finally
            ' Clean things up.
            ' Close the streams.
            If Not (srDecrypt Is Nothing) Then
                srDecrypt.Close()
            End If
            If Not (csDecrypt Is Nothing) Then
                csDecrypt.Close()
            End If
            If Not (msDecrypt Is Nothing) Then
                msDecrypt.Close()
            End If
            ' Clear the RijndaelManaged object.
            If Not (aesAlg Is Nothing) Then
                aesAlg.Clear()
            End If
        End Try
        Return plaintext

    End Function
End Module

C#
using System;
using System.IO;
using System.Security.Cryptography;

namespace RijndaelManaged_Examples
{
    class RijndaelMemoryExample
    {
        public static void Main()
        {
            try
            {

                string original = "Here is some data to encrypt!";

                // Create a new instance of the RijndaelManaged
                // class.  This generates a new key and initialization 
                // vector (IV).
                RijndaelManaged myRijndael = new RijndaelManaged();

                // Encrypt the string to an array of bytes.
                byte[] encrypted = encryptStringToBytes_AES(original, myRijndael.Key, myRijndael.IV);  

                // Decrypt the bytes to a string.
                string roundtrip = decryptStringFromBytes_AES(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_AES(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");

            // Declare the streams used
            // to encrypt to an in memory
            // array of bytes.
            MemoryStream    msEncrypt   = null;
            CryptoStream    csEncrypt   = null;
            StreamWriter    swEncrypt   = null;

            // Declare the RijndaelManaged object
            // used to encrypt the data.
            RijndaelManaged aesAlg      = null;

            // Declare the bytes used to hold the
            // encrypted data.
            byte[]          encrypted   = null;

            try
            {
                // Create a RijndaelManaged object
                // with the specified key and IV.
                aesAlg = new RijndaelManaged();
                aesAlg.Key = Key;
                aesAlg.IV = IV;

                // Create a decrytor to perform the stream transform.
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for encryption.
                msEncrypt = new MemoryStream();
                csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
                swEncrypt = new StreamWriter(csEncrypt);

                //Write all data to the stream.
                swEncrypt.Write(plainText);

            }
            finally
            {
                // Clean things up.

                // Close the streams.
                if(swEncrypt != null)
                    swEncrypt.Close();
                if (csEncrypt != null)
                    csEncrypt.Close();
                if (msEncrypt != null)
                    msEncrypt.Close();

                // Clear the RijndaelManaged object.
                if (aesAlg != null)
                    aesAlg.Clear();
            }

            // Return the encrypted bytes from the memory stream.
            return msEncrypt.ToArray();

        }

        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");

            // TDeclare the streams used
            // to decrypt to an in memory
            // array of bytes.
            MemoryStream    msDecrypt   = null;
            CryptoStream    csDecrypt   = null;
            StreamReader    srDecrypt   = null;

            // Declare the RijndaelManaged object
            // used to decrypt the data.
            RijndaelManaged aesAlg      = null;

            // Declare the string used to hold
            // the decrypted text.
            string plaintext = null;

            try
            {
                // Create a RijndaelManaged object
                // with the specified key and IV.
                aesAlg = new RijndaelManaged();
                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.
                msDecrypt = new MemoryStream(cipherText);
                csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
                srDecrypt = new StreamReader(csDecrypt);

                // Read the decrypted bytes from the decrypting stream
                // and place them in a string.
                plaintext = srDecrypt.ReadToEnd();
            }
            finally
            {
                // Clean things up.

                // Close the streams.
                if (srDecrypt != null)
                    srDecrypt.Close();
                if (csDecrypt != null)
                    csDecrypt.Close();
                if (msDecrypt != null)
                    msDecrypt.Close();

                // Clear the RijndaelManaged object.
                if (aesAlg != null)
                    aesAlg.Clear();
            }

            return plaintext;

        }
    }
}

Visual C++
#using <System.dll>

using namespace System;
using namespace System::IO;
using namespace System::Security::Cryptography;


class RijndaelMemoryExample
{
 public:
    static array<Byte> ^ encryptStringToBytes_AES(String^ plainText, array<Byte> ^ Key, array<Byte> ^ IV)
    {
        // Check arguments.
        if (!plainText || plainText->Length <= 0)
            throw gcnew ArgumentNullException("plainText");
        if (!Key || Key->Length <= 0)
            throw gcnew ArgumentNullException("Key");
        if (!IV  || IV->Length <= 0)
            throw gcnew ArgumentNullException("Key");

        // Declare the streams used
        // to encrypt to an in memory
        // array of bytes.
        MemoryStream ^   msEncrypt;
        CryptoStream ^   csEncrypt;
        StreamWriter ^   swEncrypt;

        // Declare the RijndaelManaged object
        // used to encrypt the data.
        RijndaelManaged ^ aesAlg;

        try
        {
            // Create a RijndaelManaged object
            // with the specified key and IV.
            aesAlg = gcnew RijndaelManaged();
            aesAlg->Key = Key;
            aesAlg->IV = IV;

            // Create a decrytor to perform the stream transform.
            ICryptoTransform ^ encryptor = aesAlg->CreateEncryptor(aesAlg->Key, aesAlg->IV);

            // Create the streams used for encryption.
            msEncrypt = gcnew MemoryStream();
            csEncrypt = gcnew CryptoStream(msEncrypt, encryptor, CryptoStreamMode::Write);
            swEncrypt = gcnew StreamWriter(csEncrypt);

            //Write all data to the stream.
            swEncrypt->Write(plainText);

        }
        finally
        {
            // Clean things up.

            // Close the streams.
            if(swEncrypt)
                swEncrypt->Close();
            if (csEncrypt)
                csEncrypt->Close();
            if (msEncrypt)
                msEncrypt->Close();

            // Clear the RijndaelManaged object.
            if (aesAlg)
                aesAlg->Clear();
        }

        // Return the encrypted bytes from the memory stream.
        return msEncrypt->ToArray();

    }

    static String ^ decryptStringFromBytes_AES(array<Byte> ^ cipherText, array<Byte> ^ Key, array<Byte> ^ IV)
    {
        // Check arguments.
        if (!cipherText || cipherText->Length <= 0)
            throw gcnew ArgumentNullException("cipherText");
        if (!Key || Key->Length <= 0)
            throw gcnew ArgumentNullException("Key");
        if (!IV || IV->Length <= 0)
            throw gcnew ArgumentNullException("Key");

        // TDeclare the streams used
        // to decrypt to an in memory
        // array of bytes.
        MemoryStream   ^ msDecrypt;
        CryptoStream   ^ csDecrypt;
        StreamReader   ^ srDecrypt;

        // Declare the RijndaelManaged object
        // used to decrypt the data.
        RijndaelManaged ^ aesAlg;

        // Declare the string used to hold
        // the decrypted text.
        String ^ plaintext;

        try
        {
            // Create a RijndaelManaged object
            // with the specified key and IV.
            aesAlg = gcnew RijndaelManaged();
            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.
            msDecrypt = gcnew MemoryStream(cipherText);
            csDecrypt = gcnew CryptoStream(msDecrypt, decryptor, CryptoStreamMode::Read);
            srDecrypt = gcnew StreamReader(csDecrypt);

            // Read the decrypted bytes from the decrypting stream
            // and place them in a string.
            plaintext = srDecrypt->ReadToEnd();
        }
        finally
        {
            // Clean things up.

            // Close the streams.
            if (srDecrypt)
                srDecrypt->Close();
            if (csDecrypt)
                csDecrypt->Close();
            if (msDecrypt)
                msDecrypt->Close();

            // Clear the RijndaelManaged object.
            if (aesAlg)
                aesAlg->Clear();
        }

        return plaintext;

    }

};

int main()
{
    try
    {

        String ^ original = "Here is some data to encrypt!";

        // Create a new instance of the RijndaelManaged
        // class.  This generates a new key and initialization
        // vector (IV).
        RijndaelManaged ^ myRijndael = gcnew RijndaelManaged();

        // Encrypt the string to an array of bytes.
        array<Byte> ^ encrypted = RijndaelMemoryExample::encryptStringToBytes_AES(original, myRijndael->Key, myRijndael->IV);

        // Decrypt the bytes to a string.
        String ^ roundtrip = RijndaelMemoryExample::decryptStringFromBytes_AES(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);
    }

    return 0;
}


Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC

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

.NET Framework

Supported in: 3.5, 3.0 SP1, 3.0, 2.0 SP1, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 3.5, 2.0
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content      
Processing
© 2008 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker