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)

'Declaration
Public NotInheritable Class AesManaged _
	Inherits 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 PhoneCreateDecryptorCreates 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 PhoneCreateEncryptorCreates 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>



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


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