AesManaged Класс

Определение

Предоставляет управляемую реализацию симметричного алгоритма расширенного шифрования (AES).

public ref class AesManaged sealed : System::Security::Cryptography::Aes
public sealed class AesManaged : System.Security.Cryptography.Aes
type AesManaged = class
    inherit Aes
Public NotInheritable Class AesManaged
Inherits Aes
Наследование

Примеры

В следующем примере показано, как шифровать и расшифровывать примеры данных с помощью AesManaged класса.

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

namespace Aes_Example
{
    class AesExample
    {
        public static void Main()
        {
            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.
                Console.WriteLine("Original:   {0}", original);
                Console.WriteLine("Round Trip: {0}", roundtrip);
            }
        }
        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("IV");
            byte[] encrypted;

            // Create an AesManaged object
            // with the specified key and IV.
            using (AesManaged aesAlg = new AesManaged())
            {
                aesAlg.Key = Key;
                aesAlg.IV = IV;

                // Create an encryptor 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("IV");

            // 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 decryptor 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;
        }
    }
}
Imports System.IO
Imports System.Security.Cryptography



Class AesExample

    Public Shared Sub Main()
        Dim original As String = "Here is some data to encrypt!"

        ' Create a new instance of the AesManaged
        ' class.  This generates a new key and initialization 
        ' vector (IV).
        Using myAes As New AesManaged()
            ' Encrypt the string to an array of bytes.
            Dim encrypted As Byte() = EncryptStringToBytes_Aes(original, myAes.Key, myAes.IV)

            ' Decrypt the bytes to a string.
            Dim roundtrip As String = DecryptStringFromBytes_Aes(encrypted, myAes.Key, myAes.IV)

            'Display the original data and the decrypted data.
            Console.WriteLine("Original:   {0}", original)
            Console.WriteLine("Round Trip: {0}", roundtrip)
        End Using

    End Sub

    Shared Function EncryptStringToBytes_Aes(ByVal plainText As String, ByVal Key() As Byte, ByVal IV() As Byte) As Byte()
        ' Check arguments.
        If plainText Is Nothing OrElse plainText.Length <= 0 Then
            Throw New ArgumentNullException("plainText")
        End If
        If Key Is Nothing OrElse Key.Length <= 0 Then
            Throw New ArgumentNullException("Key")
        End If
        If IV Is Nothing OrElse IV.Length <= 0 Then
            Throw New ArgumentNullException("IV")
        End If
        Dim encrypted() As Byte
        
        ' Create an AesManaged object
        ' with the specified key and IV.
        Using aesAlg As New AesManaged()

            aesAlg.Key = Key
            aesAlg.IV = IV

            ' Create an encryptor to perform the stream transform.
            Dim encryptor As ICryptoTransform = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV)
            ' Create the streams used for encryption.
            Using msEncrypt As New MemoryStream()
                Using csEncrypt As New CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)
                    Using swEncrypt As New StreamWriter(csEncrypt)
                        'Write all data to the stream.
                        swEncrypt.Write(plainText)
                    End Using
                    encrypted = msEncrypt.ToArray()
                End Using
            End Using
        End Using

        ' Return the encrypted bytes from the memory stream.
        Return encrypted

    End Function 'EncryptStringToBytes_Aes

    Shared Function DecryptStringFromBytes_Aes(ByVal cipherText() As Byte, ByVal Key() As Byte, ByVal IV() As Byte) As String
        ' Check arguments.
        If cipherText Is Nothing OrElse cipherText.Length <= 0 Then
            Throw New ArgumentNullException("cipherText")
        End If
        If Key Is Nothing OrElse Key.Length <= 0 Then
            Throw New ArgumentNullException("Key")
        End If
        If IV Is Nothing OrElse IV.Length <= 0 Then
            Throw New ArgumentNullException("IV")
        End If
        ' Declare the string used to hold
        ' the decrypted text.
        Dim plaintext As String = Nothing

        ' Create an AesManaged object
        ' with the specified key and IV.
        Using aesAlg As New AesManaged
            aesAlg.Key = Key
            aesAlg.IV = IV

            ' Create a decryptor to perform the stream transform.
            Dim decryptor As ICryptoTransform = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV)

            ' Create the streams used for decryption.
            Using msDecrypt As New MemoryStream(cipherText)

                Using csDecrypt As New CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)

                    Using srDecrypt As New StreamReader(csDecrypt)


                        ' Read the decrypted bytes from the decrypting stream
                        ' and place them in a string.
                        plaintext = srDecrypt.ReadToEnd()
                    End Using
                End Using
            End Using
        End Using

        Return plaintext

    End Function 'DecryptStringFromBytes_Aes 
End Class
open System
open System.IO
open System.Security.Cryptography

let encryptStringToBytes_Aes (plainText: string, key : byte[], iv : byte[]) : byte[] =

    // Check arguments.
    if (isNull plainText || plainText.Length <= 0) then nullArg "plainText"
    if (isNull key || key.Length <= 0) then nullArg "key"
    if (isNull iv || iv.Length <= 0) then nullArg "iv"
    
    // Create an AesManaged object
    // with the specified key and IV.
    use aesAlg = new AesManaged()
    aesAlg.Key <- key
    aesAlg.IV <- iv

    // Create an encryptor to perform the stream transform.
    let encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV)

    // Create the streams used for encryption.
    use msEncrypt = new MemoryStream()
    use csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)
    use swEncrypt = new StreamWriter(csEncrypt)
    
    //Write all data to the stream.
    swEncrypt.Write(plainText)
    swEncrypt.Flush()
    
    // Return the encrypted bytes from the memory stream.
    msEncrypt.ToArray()

let decryptStringFromBytes_Aes (cipherText : byte[], key : byte[], iv : byte[]) : string =

    // Check arguments.
    if (isNull cipherText || cipherText.Length <= 0) then nullArg "cipherText"
    if (isNull key || key.Length <= 0) then nullArg "key"
    if (isNull iv || iv.Length <= 0) then nullArg "iv"

    // Create an AesManaged object
    // with the specified key and IV.
    use aesAlg = new AesManaged()
    aesAlg.Key <- key
    aesAlg.IV <- iv

    // Create a decryptor to perform the stream transform.
    let decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV)

    // Create the streams used for decryption.
    use msDecrypt = new MemoryStream(cipherText)
    use csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)
    use srDecrypt = new StreamReader(csDecrypt)

    // Read the decrypted bytes from the decrypting stream
    // and return the resulting string.
    srDecrypt.ReadToEnd()

[<EntryPoint>]
let main argv = 

    let original = "Here is some data to encrypt!"

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

    // Encrypt the string to an array of bytes.
    let encrypted = encryptStringToBytes_Aes(original, myAes.Key, myAes.IV)

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

    //Display the original data and the decrypted data.
    Console.WriteLine("Original:   {0}", original)
    Console.WriteLine("Round Trip: {0}", roundtrip)
    0

Комментарии

Алгоритм AES по сути является симметричным алгоритмом Rijndael с фиксированным размером блока и числом итерации. Этот класс работает так же, как RijndaelManaged класс, но ограничивает блоки до 128 бит и не разрешает режимы обратной связи.

Note

Если включен параметр политики безопасности Windows для алгоритмов, совместимых с федеральными стандартами обработки информации (FIPS), этот алгоритм создает CryptographicException.

Note

Microsoft считает, что шифрование данных, зашифрованных с помощью режима шифрованияBlock-Chaining (CBC) симметричного шифрования (которое является значением по умолчанию свойства Mode), если проверяемое заполнение было применено без первого обеспечения целостности шифра, за исключением очень конкретных обстоятельств. Дополнительные сведения см. в статье Об уязвимостях времени с симметричным расшифровкой в режиме CBC с помощью заполнения.

Конструкторы

Имя Описание
AesManaged()

Инициализирует новый экземпляр класса AesManaged.

Поля

Имя Описание
BlockSizeValue

Представляет размер блока в битах криптографической операции.

(Унаследовано от SymmetricAlgorithm)
FeedbackSizeValue

Представляет размер обратной связи (в битах) криптографической операции.

(Унаследовано от SymmetricAlgorithm)
IVValue

Представляет вектор инициализации (IV) для симметричного алгоритма.

(Унаследовано от SymmetricAlgorithm)
KeySizeValue

Представляет размер в битах секретного ключа, используемого симметричным алгоритмом.

(Унаследовано от SymmetricAlgorithm)
KeyValue

Представляет секретный ключ для симметричного алгоритма.

(Унаследовано от SymmetricAlgorithm)
LegalBlockSizesValue

Указывает размеры блоков в битах, поддерживаемые симметричным алгоритмом.

(Унаследовано от SymmetricAlgorithm)
LegalKeySizesValue

Указывает размеры ключей в битах, поддерживаемые симметричным алгоритмом.

(Унаследовано от SymmetricAlgorithm)
ModeValue

Представляет режим шифра, используемый в симметричном алгоритме.

(Унаследовано от SymmetricAlgorithm)
PaddingValue

Представляет режим заполнения, используемый в симметричном алгоритме.

(Унаследовано от SymmetricAlgorithm)

Свойства

Имя Описание
BlockSize

Возвращает или задает размер блока в битах криптографической операции.

BlockSize

Возвращает или задает размер блока в битах криптографической операции.

(Унаследовано от SymmetricAlgorithm)
FeedbackSize

Возвращает или задает количество битов, используемых в качестве обратной связи.

IV

Получает или задает вектор инициализации (IV), используемый для симметричного алгоритма.

Key

Возвращает или задает секретный ключ, используемый для симметричного алгоритма.

KeySize

Возвращает или задает размер в битах секретного ключа, используемого для симметричного алгоритма.

LegalBlockSizes

Возвращает размеры блоков в битах, поддерживаемые симметричным алгоритмом.

LegalKeySizes

Возвращает размеры ключей в битах, поддерживаемые симметричным алгоритмом.

Mode

Возвращает или задает режим для работы симметричного алгоритма.

Padding

Возвращает или задает режим заполнения, используемый в симметричном алгоритме.

Методы

Имя Описание
Clear()

Освобождает все ресурсы, используемые классом SymmetricAlgorithm .

(Унаследовано от SymmetricAlgorithm)
CreateDecryptor()

Создает объект симметричного расшифровки с помощью текущего ключа и вектора инициализации (IV).

CreateDecryptor(Byte[], Byte[])

Создает объект симметричного расшифровки с помощью указанного ключа и вектора инициализации (IV).

CreateEncryptor()

Создает объект симметричного шифрования с помощью текущего ключа и вектора инициализации (IV).

CreateEncryptor(Byte[], Byte[])

Создает объект симметричного шифрования с помощью указанного ключа и вектора инициализации (IV).

Dispose()

Освобождает все ресурсы, используемые текущим экземпляром класса SymmetricAlgorithm.

(Унаследовано от SymmetricAlgorithm)
Dispose(Boolean)

Освобождает неуправляемые ресурсы, используемые SymmetricAlgorithm и при необходимости освобождает управляемые ресурсы.

(Унаследовано от SymmetricAlgorithm)
Equals(Object)

Определяет, равен ли указанный объект текущему объекту.

(Унаследовано от Object)
GenerateIV()

Создает вектор случайной инициализации (IV), используемый для симметричного алгоритма.

GenerateKey()

Создает случайный ключ, используемый для симметричного алгоритма.

GetHashCode()

Служит хэш-функцией по умолчанию.

(Унаследовано от Object)
GetType()

Возвращает Type текущего экземпляра.

(Унаследовано от Object)
MemberwiseClone()

Создает неглубокую копию текущей Object.

(Унаследовано от Object)
ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)
ValidKeySize(Int32)

Определяет, является ли указанный размер ключа допустимым для текущего алгоритма.

(Унаследовано от SymmetricAlgorithm)

Явные реализации интерфейса

Имя Описание
IDisposable.Dispose()

Этот API поддерживает инфраструктуру продукта и не предназначен для использования непосредственно из программного кода.

Освобождает неуправляемые ресурсы, используемые SymmetricAlgorithm и при необходимости освобождает управляемые ресурсы.

(Унаследовано от SymmetricAlgorithm)

Применяется к