Export (0) Print
Expand All

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 methodSupported by Silverlight for Windows PhoneAesManagedInitializes a new instance of the AesManaged class.
Top

  NameDescription
Public propertySupported by Silverlight for Windows PhoneBlockSizeGets or sets the block size, in bits, of the cryptographic operation. (Inherited from SymmetricAlgorithm.)
Public propertySupported by Silverlight for Windows PhoneIVGets or sets the initialization vector (IV) to use for the symmetric algorithm. (Overrides SymmetricAlgorithm.IV.)
Public propertySupported by Silverlight for Windows PhoneKeyGets or sets the secret key used for the symmetric algorithm. (Overrides SymmetricAlgorithm.Key.)
Public propertySupported by Silverlight for Windows PhoneKeySizeGets or sets the size, in bits, of the secret key used for the symmetric algorithm. (Overrides SymmetricAlgorithm.KeySize.)
Public propertySupported by Silverlight for Windows PhoneLegalBlockSizesGets the block sizes, in bits, that are supported by the symmetric algorithm. (Inherited from SymmetricAlgorithm.)
Public propertySupported by Silverlight for Windows PhoneLegalKeySizesGets the key sizes, in bits, that are supported by the symmetric algorithm. (Inherited from SymmetricAlgorithm.)
Top

  NameDescription
Public methodSupported by Silverlight for Windows PhoneClearReleases all resources used by the SymmetricAlgorithm class. (Inherited from SymmetricAlgorithm.)
Public methodSupported by Silverlight for Windows PhoneCreateDecryptor()Creates a symmetric decryptor object using the current key and initialization vector (IV). (Overrides SymmetricAlgorithm.CreateDecryptor().)
Public methodSupported by Silverlight for Windows PhoneCreateDecryptor(Byte[], Byte[])Creates a symmetric decryptor object using the specified key and initialization vector (IV). (Overrides SymmetricAlgorithm.CreateDecryptor(Byte[], Byte[]).)
Public methodSupported by Silverlight for Windows PhoneCreateEncryptor()Creates a symmetric encryptor object using the current key and initialization vector (IV). (Overrides SymmetricAlgorithm.CreateEncryptor().)
Public methodSupported by Silverlight for Windows PhoneCreateEncryptor(Byte[], Byte[])Creates a symmetric encryptor object using the specified key and initialization vector (IV). (Overrides SymmetricAlgorithm.CreateEncryptor(Byte[], Byte[]).)
Protected methodSupported by Silverlight for Windows PhoneDisposeReleases the unmanaged resources used by the SymmetricAlgorithm and optionally releases the managed resources. (Inherited from SymmetricAlgorithm.)
Public methodSupported by Silverlight for Windows PhoneEquals(Object)Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected methodSupported by Silverlight for Windows PhoneFinalizeAllows an object to try to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)
Public methodSupported by Silverlight for Windows PhoneGenerateIVGenerates a random initialization vector (IV) to use for the symmetric algorithm. (Overrides SymmetricAlgorithm.GenerateIV().)
Public methodSupported by Silverlight for Windows PhoneGenerateKeyGenerates a random key to use for the symmetric algorithm. (Overrides SymmetricAlgorithm.GenerateKey().)
Public methodSupported by Silverlight for Windows PhoneGetHashCodeServes as a hash function for a particular type. (Inherited from Object.)
Public methodSupported by Silverlight for Windows PhoneGetTypeGets the Type of the current instance. (Inherited from Object.)
Protected methodSupported by Silverlight for Windows PhoneMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodSupported by Silverlight for Windows PhoneToStringReturns a string that represents the current object. (Inherited from Object.)
Public methodSupported by Silverlight for Windows PhoneValidKeySizeDetermines whether the specified key size is valid for the current algorithm. (Inherited from SymmetricAlgorithm.)
Top

  NameDescription
Protected fieldSupported by Silverlight for Windows PhoneBlockSizeValueRepresents the block size, in bits, of the cryptographic operation. (Inherited from SymmetricAlgorithm.)
Protected fieldSupported by Silverlight for Windows PhoneIVValueRepresents the initialization vector (IV) for the symmetric algorithm. (Inherited from SymmetricAlgorithm.)
Protected fieldSupported by Silverlight for Windows PhoneKeySizeValueRepresents the size, in bits, of the secret key used by the symmetric algorithm. (Inherited from SymmetricAlgorithm.)
Protected fieldSupported by Silverlight for Windows PhoneKeyValueRepresents the secret key for the symmetric algorithm. (Inherited from SymmetricAlgorithm.)
Protected fieldSupported by Silverlight for Windows PhoneLegalBlockSizesValueSpecifies the block sizes, in bits, that are supported by the symmetric algorithm. (Inherited from SymmetricAlgorithm.)
Protected fieldSupported by Silverlight for Windows PhoneLegalKeySizesValueSpecifies the key sizes, in bits, that are supported by the symmetric algorithm. (Inherited from SymmetricAlgorithm.)
Top

  NameDescription
Explicit interface implemetationPrivate methodSupported by Silverlight for Windows PhoneIDisposable.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 Silverlight-based application 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.


<UserControl x:Class="AESManaged.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width="1024" Height="768">
    <Grid x:Name="LayoutRoot" Background="White" >
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="350" />
            <ColumnDefinition Width="250" />
            <!--<ColumnDefinition Width="250" />-->
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>

        <TextBlock Grid.Row="0"  Grid.Column="0" FontSize="14" Text="Enter data to encrypt"/>
        <TextBlock Grid.Row="1" Grid.Column="0" FontSize="14" Text="Enter password and press Enter to encrypt" />
        <TextBlock Grid.Row="2" Grid.Column="0" FontSize="14" Text="Enter file to decrypt" />
        <TextBlock Grid.Row="3" Grid.Column="0" FontSize="14" Text="Enter password and press Enter to decrypt" />
        <TextBlock Grid.Row="4" Grid.Column="0" FontSize="14" Text="Enter file name to delete" />
        <TextBox x:Name="inputBox" Grid.Row="0" Grid.Column="1" TabIndex="0" FontSize="12" IsReadOnly="False"  BorderThickness="5" Height="40"  Width="160" HorizontalAlignment="Center" />
        <PasswordBox x:Name="passwordBox" Grid.Row="1" Grid.Column="1" TabIndex ="1" FontSize="12"  BorderThickness="5" Height="40"  Width="160" HorizontalAlignment="Center" />
        <TextBox x:Name="decryptBox" Grid.Row="2" Grid.Column="1" TabIndex="2" FontSize="12" IsReadOnly="False"  BorderThickness="5" Height="40"  Width="160" HorizontalAlignment="Center" />
        <PasswordBox x:Name="decryptPassWordBox" Grid.Row="3" TabIndex="3" Grid.Column="1" FontSize="12" BorderThickness="5" Height="40"  Width="160" HorizontalAlignment="Center" />
        <TextBox x:Name="deleteBox" Grid.Row="4" Grid.Column="1" TabIndex="4" FontSize="12" IsReadOnly="False"  BorderThickness="5" Height="40"  Width="160" HorizontalAlignment="Center" />
        <TextBlock x:Name="outputBlock" Grid.Row="5" Grid.Column="0" FontSize="12" TextWrapping="Wrap">
        </TextBlock>
    </Grid>
</UserControl>



<UserControl x:Class="AESManaged.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width="1024" Height="768">
    <Grid x:Name="LayoutRoot" Background="White" >
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="350" />
            <ColumnDefinition Width="250" />
            <!--<ColumnDefinition Width="250" />-->
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>

        <TextBlock Grid.Row="0"  Grid.Column="0" FontSize="14" Text="Enter data to encrypt"/>
        <TextBlock Grid.Row="1" Grid.Column="0" FontSize="14" Text="Enter password and press Enter to encrypt" />
        <TextBlock Grid.Row="2" Grid.Column="0" FontSize="14" Text="Enter file to decrypt" />
        <TextBlock Grid.Row="3" Grid.Column="0" FontSize="14" Text="Enter password and press Enter to decrypt" />
        <TextBlock Grid.Row="4" Grid.Column="0" FontSize="14" Text="Enter file name to delete" />
        <TextBox x:Name="inputBox" Grid.Row="0" Grid.Column="1" TabIndex="0" FontSize="12" IsReadOnly="False"  BorderThickness="5" Height="40"  Width="160" HorizontalAlignment="Center" />
        <PasswordBox x:Name="passwordBox" Grid.Row="1" Grid.Column="1" TabIndex ="1" FontSize="12"  BorderThickness="5" Height="40"  Width="160" HorizontalAlignment="Center" />
        <TextBox x:Name="decryptBox" Grid.Row="2" Grid.Column="1" TabIndex="2" FontSize="12" IsReadOnly="False"  BorderThickness="5" Height="40"  Width="160" HorizontalAlignment="Center" />
        <PasswordBox x:Name="decryptPassWordBox" Grid.Row="3" TabIndex="3" Grid.Column="1" FontSize="12" BorderThickness="5" Height="40"  Width="160" HorizontalAlignment="Center" />
        <TextBox x:Name="deleteBox" Grid.Row="4" Grid.Column="1" TabIndex="4" FontSize="12" IsReadOnly="False"  BorderThickness="5" Height="40"  Width="160" HorizontalAlignment="Center" />
        <TextBlock x:Name="outputBlock" Grid.Row="5" Grid.Column="0" FontSize="12" TextWrapping="Wrap">
        </TextBlock>
    </Grid>
</UserControl>



using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.IO.IsolatedStorage;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
namespace AESManaged
{
    public partial class MainPage : UserControl
    {
        private static string encryptedFiles = "";
        private static IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForSite();
        private const string PasswordSalt = "PasswordSalt";
        public MainPage()
        {
            InitializeComponent();
            this.inputBox.KeyDown += new KeyEventHandler(inputBox_KeyDown);
            this.passwordBox.KeyDown += new KeyEventHandler(passwordBox_KeyDown);
            this.decryptPassWordBox.KeyDown += new KeyEventHandler(decryptPassWordBox_KeyDown);
            this.deleteBox.KeyDown += new KeyEventHandler(deleteBox_KeyDown);

            store.CreateDirectory("MyFiles");

            // Create subdirectory under MyFiles.
            encryptedFiles = System.IO.Path.Combine("MyFiles", "EncryptedFiles");

            store.CreateDirectory(encryptedFiles);
            ListFiles();
            inputBox.Focus();
        }
        private void inputBox_KeyDown(object sender, EventArgs e)
        {
            if (((System.Windows.Input.KeyEventArgs)e).Key == Key.Enter)
            {
                this.passwordBox.Focus();
            }
        }
        private void ListFiles()
        {
            string searchpath = System.IO.Path.Combine(encryptedFiles, "*.*");
            string[] filesInSubDirs = store.GetFileNames(searchpath);
            StringBuilder sb = new StringBuilder();
            // List files in MyFiles\EncryptedFiles.
            sb.AppendLine(@"Files in MyFiles\EncryptedFiles:");
            foreach (string fileName in filesInSubDirs)
            {
                sb.AppendLine(" - " + fileName);
            }
            sb.AppendLine();
            outputBlock.Text = sb.ToString();
        }
        private void deleteBox_KeyDown(object sender, EventArgs e)
        {

            if (((System.Windows.Input.KeyEventArgs)e).Key == Key.Enter)
            {
                store.DeleteFile(encryptedFiles + "\\" + deleteBox.Text);
                ListFiles();
                this.passwordBox.Focus();
            }
        }
        private void passwordBox_KeyDown(object sender, EventArgs e)
        {
            if (((System.Windows.Input.KeyEventArgs)e).Key == Key.Enter)
            {
                Encrypt();
                this.decryptBox.Focus();
            }

        }
        private void decryptPassWordBox_KeyDown(object sender, EventArgs e)
        {
            if (((System.Windows.Input.KeyEventArgs)e).Key == Key.Enter)
            {
                outputBlock.Text = Decrypt();
                this.deleteBox.Focus();
            }
        }
        private string Decrypt()
        {
            IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
            string encryptedFiles = System.IO.Path.Combine("MyFiles", "EncryptedFiles");
            store.CreateDirectory(encryptedFiles);
            string xFilePath = System.IO.Path.Combine(encryptedFiles, decryptBox.Text);

            using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
            using (IsolatedStorageFileStream isoStoreStream = isoStore.OpenFile(xFilePath, FileMode.Open))
            {
                using (Aes aes = new AesManaged())
                {
                    Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(decryptPassWordBox.Password, Encoding.UTF8.GetBytes(PasswordSalt));
                    aes.Key = deriveBytes.GetBytes(128 / 8);
                    // Get the initialization vector from the encrypted stream
                    aes.IV = ReadByteArray(isoStoreStream);
                    CryptoStream cs = new CryptoStream(isoStoreStream, aes.CreateDecryptor(), CryptoStreamMode.Read);
                    StreamReader reader = new StreamReader(cs, Encoding.Unicode);
                    try
                    {
                        string retval = reader.ReadToEnd();
                        reader.Dispose();
                        cs.Dispose();
                        return retval;
                    }
                    catch (Exception e)
                    {
                        return e.ToString();
                    }

                }
            }
        }
        private void Encrypt()
        {
            IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
            string encryptedFiles = System.IO.Path.Combine("MyFiles", "EncryptedFiles");
            store.CreateDirectory(encryptedFiles);
            string xFilePath = System.IO.Path.Combine(encryptedFiles, "encryptedFile.txt");
            IsolatedStorageFileStream xStream = store.CreateFile(xFilePath);
            xStream.Close();
            decryptBox.Text = "encryptedFile.txt";
            using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
            using (IsolatedStorageFileStream isoStoreStream = isoStore.OpenFile(xFilePath, FileMode.Create))
            {
                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();
                    }
                }
            }
            xStream.Close();
            xStream =
                store.OpenFile(System.IO.Path.Combine(encryptedFiles, "encryptedFile.txt"), FileMode.Open);
            StreamReader reader = new StreamReader(xStream);
            // Read the data.
            this.outputBlock.Text = reader.ReadToEnd();
            reader.Close();
            xStream.Close();
        }
        private static byte[] ReadByteArray(Stream s)
        {
            byte[] rawLength = new byte[sizeof(int)];
            if (s.Read(rawLength, 0, rawLength.Length) != rawLength.Length)
            {
                throw new SystemException("Stream did not contain properly formatted byte array");
            }

            byte[] buffer = new byte[BitConverter.ToInt32(rawLength, 0)];
            if (s.Read(buffer, 0, buffer.Length) != buffer.Length)
            {
                throw new SystemException("Did not read byte array properly");
            }

            return buffer;
        }

    }
}


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

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

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Community Additions

ADD
Show:
© 2014 Microsoft