AesManaged Class
Provides a managed implementation of the Advanced Encryption Standard (AES) symmetric algorithm.
System.Security.Cryptography.SymmetricAlgorithm
System.Security.Cryptography.Aes
System.Security.Cryptography.AesManaged
Namespace: System.Security.Cryptography
Assembly: System.Core (in System.Core.dll)
The AesManaged type exposes the following members.
| Name | Description | |
|---|---|---|
![]() ![]() | BlockSize | Gets or sets the block size, in bits, of the cryptographic operation. (Inherited from SymmetricAlgorithm.) |
![]() ![]() | IV | Gets or sets the initialization vector (IV) to use for the symmetric algorithm. (Overrides SymmetricAlgorithm.IV.) |
![]() ![]() | Key | Gets or sets the secret key used for the symmetric algorithm. (Overrides SymmetricAlgorithm.Key.) |
![]() ![]() | KeySize | Gets or sets the size, in bits, of the secret key used for the symmetric algorithm. (Overrides SymmetricAlgorithm.KeySize.) |
![]() ![]() | LegalBlockSizes | Gets the block sizes, in bits, that are supported by the symmetric algorithm. (Inherited from SymmetricAlgorithm.) |
![]() ![]() | LegalKeySizes | Gets the key sizes, in bits, that are supported by the symmetric algorithm. (Inherited from SymmetricAlgorithm.) |
| Name | Description | |
|---|---|---|
![]() ![]() | Clear | Releases all resources used by the SymmetricAlgorithm class. (Inherited from SymmetricAlgorithm.) |
![]() ![]() | CreateDecryptor | Creates a symmetric decryptor object using the current key and initialization vector (IV). (Overrides SymmetricAlgorithm.CreateDecryptor.) |
![]() ![]() | CreateDecryptor(Byte(), Byte()) | Creates a symmetric decryptor object using the specified key and initialization vector (IV). (Overrides SymmetricAlgorithm.CreateDecryptor(Byte(), Byte()).) |
![]() ![]() | CreateEncryptor | Creates a symmetric encryptor object using the current key and initialization vector (IV). (Overrides SymmetricAlgorithm.CreateEncryptor.) |
![]() ![]() | CreateEncryptor(Byte(), Byte()) | Creates a symmetric encryptor object using the specified key and initialization vector (IV). (Overrides SymmetricAlgorithm.CreateEncryptor(Byte(), Byte()).) |
![]() ![]() | Dispose | Releases the unmanaged resources used by the SymmetricAlgorithm and optionally releases the managed resources. (Inherited from SymmetricAlgorithm.) |
![]() ![]() | Equals(Object) | Determines whether the specified Object is equal to the current Object. (Inherited from Object.) |
![]() ![]() | Finalize | Allows an object to try to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.) |
![]() ![]() | GenerateIV | Generates a random initialization vector (IV) to use for the symmetric algorithm. (Overrides SymmetricAlgorithm.GenerateIV.) |
![]() ![]() | GenerateKey | Generates a random key to use for the symmetric algorithm. (Overrides SymmetricAlgorithm.GenerateKey.) |
![]() ![]() | GetHashCode | Serves as a hash function for a particular type. (Inherited from Object.) |
![]() ![]() | GetType | Gets the Type of the current instance. (Inherited from Object.) |
![]() ![]() | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.) |
![]() ![]() | ToString | Returns a string that represents the current object. (Inherited from Object.) |
![]() ![]() | ValidKeySize | Determines whether the specified key size is valid for the current algorithm. (Inherited from SymmetricAlgorithm.) |
| Name | Description | |
|---|---|---|
![]() ![]() | BlockSizeValue | Represents the block size, in bits, of the cryptographic operation. (Inherited from SymmetricAlgorithm.) |
![]() ![]() | IVValue | Represents the initialization vector (IV) for the symmetric algorithm. (Inherited from SymmetricAlgorithm.) |
![]() ![]() | KeySizeValue | Represents the size, in bits, of the secret key used by the symmetric algorithm. (Inherited from SymmetricAlgorithm.) |
![]() ![]() | KeyValue | Represents the secret key for the symmetric algorithm. (Inherited from SymmetricAlgorithm.) |
![]() ![]() | LegalBlockSizesValue | Specifies the block sizes, in bits, that are supported by the symmetric algorithm. (Inherited from SymmetricAlgorithm.) |
![]() ![]() | LegalKeySizesValue | Specifies the key sizes, in bits, that are supported by the symmetric algorithm. (Inherited from SymmetricAlgorithm.) |
| Name | Description | |
|---|---|---|
![]() ![]() ![]() | IDisposable.Dispose | Infrastructure. Releases the unmanaged resources used by the SymmetricAlgorithm and optionally releases the managed resources. (Inherited from SymmetricAlgorithm.) |
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.
Note: |
|---|
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>
Imports System Imports System.Windows.Controls Imports System.Windows.Input Imports System.IO Imports System.IO.IsolatedStorage Imports System.Security.Cryptography Imports System.Security.Permissions Imports System.Text Namespace AESManaged Class MainPage Inherits UserControl Private Shared encryptedFiles As String = "" Private Shared store As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForSite() Private Const PasswordSalt As String = "PasswordSalt" Private Shared intSize As Integer = 4 Public Sub New() InitializeComponent() AddHandler Me.inputBox.KeyDown, AddressOf inputBox_KeyDown AddHandler Me.passwordBox.KeyDown, AddressOf passwordBox_KeyDown AddHandler Me.decryptPassWordBox.KeyDown, AddressOf decryptPassWordBox_KeyDown AddHandler Me.deleteBox.KeyDown, AddressOf deleteBox_KeyDown store.CreateDirectory("MyFiles") ' Create subdirectory under MyFiles. encryptedFiles = System.IO.Path.Combine("MyFiles", "EncryptedFiles") store.CreateDirectory(encryptedFiles) ListFiles() inputBox.Focus() End Sub 'New Private Sub inputBox_KeyDown(ByVal sender As Object, ByVal e As EventArgs) If CType(e, System.Windows.Input.KeyEventArgs).Key = Key.Enter Then Me.passwordBox.Focus() End If End Sub 'inputBox_KeyDown Private Sub ListFiles() Dim searchpath As String = System.IO.Path.Combine(encryptedFiles, "*.*") Dim filesInSubDirs As String() = store.GetFileNames(searchpath) Dim sb As New StringBuilder() ' List files in MyFiles\EncryptedFiles. sb.AppendLine("Files in MyFiles\EncryptedFiles:") Dim fileName As String For Each fileName In filesInSubDirs sb.AppendLine(" - " + fileName) Next fileName sb.AppendLine() outputBlock.Text = sb.ToString() End Sub 'ListFiles Private Sub deleteBox_KeyDown(ByVal sender As Object, ByVal e As EventArgs) If CType(e, System.Windows.Input.KeyEventArgs).Key = Key.Enter Then store.DeleteFile(encryptedFiles + "\" + deleteBox.Text) ListFiles() Me.passwordBox.Focus() End If End Sub 'deleteBox_KeyDown Private Sub passwordBox_KeyDown(ByVal sender As Object, ByVal e As EventArgs) If CType(e, System.Windows.Input.KeyEventArgs).Key = Key.Enter Then Encrypt() Me.decryptBox.Focus() End If End Sub 'passwordBox_KeyDown Private Sub decryptPassWordBox_KeyDown(ByVal sender As Object, ByVal e As EventArgs) If CType(e, System.Windows.Input.KeyEventArgs).Key = Key.Enter Then outputBlock.Text = Decrypt() Me.deleteBox.Focus() End If End Sub 'decryptPassWordBox_KeyDown Private Function Decrypt() As String Dim store As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication() Dim encryptedFiles As String = System.IO.Path.Combine("MyFiles", "EncryptedFiles") store.CreateDirectory(encryptedFiles) Dim xFilePath As String = System.IO.Path.Combine(encryptedFiles, decryptBox.Text) Using isoStore As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication() Using isoStoreStream As IsolatedStorageFileStream = isoStore.OpenFile(xFilePath, FileMode.Open) Using aes = New System.Security.Cryptography.AesManaged() Dim deriveBytes As 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) Dim cs As New CryptoStream(isoStoreStream, aes.CreateDecryptor(), CryptoStreamMode.Read) Dim reader As New StreamReader(cs, Encoding.Unicode) Try Dim retval As String retval = reader.ReadToEnd() reader.Dispose() cs.Dispose() Return retval Catch e As Exception Return e.ToString() End Try End Using End Using End Using End Function 'Decrypt Private Sub Encrypt() Dim store As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication() Dim encryptedFiles As String = System.IO.Path.Combine("MyFiles", "EncryptedFiles") store.CreateDirectory(encryptedFiles) Dim xFilePath As String = System.IO.Path.Combine(encryptedFiles, "encryptedFile.txt") Dim xStream As IsolatedStorageFileStream = store.CreateFile(xFilePath) xStream.Close() decryptBox.Text = "encryptedFile.txt" Using isoStore As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication() Using isoStoreStream As IsolatedStorageFileStream = isoStore.OpenFile(xFilePath, FileMode.Create) 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 End Using End Using xStream.Close() xStream = store.OpenFile(System.IO.Path.Combine(encryptedFiles, "encryptedFile.txt"), FileMode.Open) Dim reader As New StreamReader(xStream) ' Read the data. Me.outputBlock.Text = reader.ReadToEnd() reader.Close() xStream.Close() End Sub 'Encrypt Private Shared Function ReadByteArray(ByVal s As Stream) As Byte() If Integer.MaxValue = Int64.MaxValue Then intSize = 8 Dim rawLength(intSize - 1) As Byte If s.Read(rawLength, 0, rawLength.Length) <> rawLength.Length Then Throw New SystemException("Stream did not contain properly formatted byte array") End If Dim buffer(BitConverter.ToInt32(rawLength, 0) - 1) As Byte If s.Read(buffer, 0, buffer.Length) <> buffer.Length Then Throw New SystemException("Did not read byte array properly") End If Return buffer End Function 'ReadByteArray End Class 'Page End Namespace
For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.
