Windows Dev Center

AesManaged Class

Provides a managed implementation of the Advanced Encryption Standard (AES) symmetric algorithm.

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

public sealed class AesManaged : Aes

The AesManaged type exposes the following members.

  NameDescription
Public methodAesManagedInitializes a new instance of the AesManaged class.
Top

  NameDescription
Public propertyBlockSizeGets or sets the block size, in bits, of the cryptographic operation. (Inherited from SymmetricAlgorithm.)
Public propertyIVGets or sets the initialization vector (IV) to use for the symmetric algorithm. (Overrides SymmetricAlgorithm.IV.)
Public propertyKeyGets or sets the secret key used for the symmetric algorithm. (Overrides SymmetricAlgorithm.Key.)
Public propertyKeySizeGets or sets the size, in bits, of the secret key used for the symmetric algorithm. (Overrides SymmetricAlgorithm.KeySize.)
Public propertyLegalBlockSizesGets the block sizes, in bits, that are supported by the symmetric algorithm. (Inherited from SymmetricAlgorithm.)
Public propertyLegalKeySizesGets the key sizes, in bits, that are supported by the symmetric algorithm. (Inherited from SymmetricAlgorithm.)
Top

  NameDescription
Public methodClearReleases all resources used by the SymmetricAlgorithm class. (Inherited from SymmetricAlgorithm.)
Public methodCreateDecryptor()Creates a symmetric decryptor object using the current key and initialization vector (IV). (Overrides SymmetricAlgorithm.CreateDecryptor().)
Public methodCreateDecryptor(Byte[], Byte[])Creates a symmetric decryptor object using the specified key and initialization vector (IV). (Overrides SymmetricAlgorithm.CreateDecryptor(Byte[], Byte[]).)
Public methodCreateEncryptor()Creates a symmetric encryptor object using the current key and initialization vector (IV). (Overrides SymmetricAlgorithm.CreateEncryptor().)
Public methodCreateEncryptor(Byte[], Byte[])Creates a symmetric encryptor object using the specified key and initialization vector (IV). (Overrides SymmetricAlgorithm.CreateEncryptor(Byte[], Byte[]).)
Protected methodDisposeReleases the unmanaged resources used by the SymmetricAlgorithm and optionally releases the managed resources. (Inherited from SymmetricAlgorithm.)
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 the Object is reclaimed by garbage collection. (Inherited from Object.)
Public methodGenerateIVGenerates a random initialization vector (IV) to use for the symmetric algorithm. (Overrides SymmetricAlgorithm.GenerateIV().)
Public methodGenerateKeyGenerates a random key to use for the symmetric algorithm. (Overrides SymmetricAlgorithm.GenerateKey().)
Public methodGetHashCodeServes as a hash function for a particular type. (Inherited from Object.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Public methodValidKeySizeDetermines whether the specified key size is valid for the current algorithm. (Inherited from SymmetricAlgorithm.)
Top

  NameDescription
Protected fieldBlockSizeValueRepresents the block size, in bits, of the cryptographic operation. (Inherited from SymmetricAlgorithm.)
Protected fieldIVValueRepresents the initialization vector (IV) for the symmetric algorithm. (Inherited from SymmetricAlgorithm.)
Protected fieldKeySizeValueRepresents the size, in bits, of the secret key used by the symmetric algorithm. (Inherited from SymmetricAlgorithm.)
Protected fieldKeyValueRepresents the secret key for the symmetric algorithm. (Inherited from SymmetricAlgorithm.)
Protected fieldLegalBlockSizesValueSpecifies the block sizes, in bits, that are supported by the symmetric algorithm. (Inherited from SymmetricAlgorithm.)
Protected fieldLegalKeySizesValueSpecifies the key sizes, in bits, that are supported by the symmetric algorithm. (Inherited from SymmetricAlgorithm.)
Top

  NameDescription
Explicit interface implemetationPrivate methodIDisposable.DisposeInfrastructure. Releases the unmanaged resources used by the SymmetricAlgorithm and optionally releases the managed resources. (Inherited from SymmetricAlgorithm.)
Top

The AES algorithm is essentially the Rijndael symmetric algorithm with a fixed block size and iteration count. This class functions the same way as the .NET Framework RijndaelManaged class but limits blocks to 128 bits and does not allow feedback modes.

The cipher mode is always CBC, and the padding mode is always PKCS7.

The following example demonstrates how to encrypt and decrypt an isolated storage file by using the AesManaged class. To build and run this example, create a Windows Phone app in Visual Studio named AesManaged and replace the MainPage.xaml file and the MainPage.xaml.cs (or MainPage.xaml.vb) file with the following code.

NoteNote:

If the XAML code is not displayed, click the Language Filter arrow at the top of this page, and select the XAML check box.


using System;
using System.IO;
using System.Security.Cryptography;

class Example
    {
   private static System.Windows.Controls.TextBlock outputBlock;

        public static void Demo(System.Windows.Controls.TextBlock outputBlock)
        {
      Example.outputBlock = outputBlock;

            try
            {

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

                // Create a new instance of the AesManaged
                // class.  This generates a new key and initialization 
                // vector (IV).
                using (AesManaged myAes = new AesManaged())
                {

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

                    // Decrypt the bytes to a string.
                    string roundtrip = DecryptStringFromBytes_Aes(encrypted, myAes.Key, myAes.IV);

                    //Display the original data and the decrypted data.
                    outputBlock.Text += String.Format("Original:   {0}", original) + Environment.NewLine;
                    outputBlock.Text += String.Format("Round Trip: {0}", roundtrip) + Environment.NewLine;
                }

            }
            catch (Exception e)
            {
                outputBlock.Text += String.Format("Error: {0}", e.Message) + Environment.NewLine;
            }
        }
        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;

        }

        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

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:
© 2015 Microsoft