AesManaged.CreateEncryptor Method (Byte[], Byte[])

Creates a symmetric encryptor object using the specified key and initialization vector (IV).

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

public override ICryptoTransform CreateEncryptor(
	byte[] key,
	byte[] iv
)

Parameters

key
Type: System.Byte[]

The secret key to use for the symmetric algorithm.

iv
Type: System.Byte[]

The initialization vector to use for the symmetric algorithm.

Return Value

Type: System.Security.Cryptography.ICryptoTransform
A symmetric encryptor object.

ExceptionCondition
ArgumentNullException

key or iv is null.

ArgumentException

key is invalid.

The following example shows how to use the CreateEncryptor method to encrypt a message. This code example is part of a larger example provided for the AesManaged class.

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");
    byte[] encrypted;
    // 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 encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.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;

}

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone Silverlight 8.1, Windows Phone Silverlight 8
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2015 Microsoft