AesCryptoServiceProvider Класс

Определение

Выполняет симметричное шифрование и расшифровку с помощью реализации интерфейсов программирования криптографических приложений (CAPI) алгоритма расширенного шифрования (AES).

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

Примеры

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

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 AesCryptoServiceProvider
            // class.  This generates a new key and initialization
            // vector (IV).
            using (AesCryptoServiceProvider myAes = new AesCryptoServiceProvider())
            {
                // 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 AesCryptoServiceProvider object
            // with the specified key and IV.
            using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
            {
                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 AesCryptoServiceProvider object
            // with the specified key and IV.
            using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
            {
                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 AesCryptoServiceProvider
        ' class.  This generates a new key and initialization 
        ' vector (IV).
        Using myAes As New AesCryptoServiceProvider()

            ' 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 AesCryptoServiceProvider object
        ' with the specified key and IV.
        Using aesAlg As New AesCryptoServiceProvider()

            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.
            Dim 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

        ' 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 AesCryptoServiceProvider object
        ' with the specified key and IV.
        Using aesAlg As New AesCryptoServiceProvider()

            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 AesCryptoServiceProvider object
    // with the specified key and IV.
    use aesAlg = new AesCryptoServiceProvider()
    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 AesCryptoServiceProvider object
    // with the specified key and IV.
    use aesAlg = new AesCryptoServiceProvider()
    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 AesCryptoServiceProvider
    // class.  This generates a new key and initialization 
    // vector (IV).
    use myAes = new AesCryptoServiceProvider()

    // 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

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

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

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

Поля

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Свойства

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

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

BlockSize

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

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

Возвращает или задает размер обратной связи (в битах) криптографической операции для режимов шифрования обратной связи (CFB) и выходных отзывов (OFB).

FeedbackSize

Возвращает или задает размер обратной связи (в битах) криптографической операции для режимов шифрования обратной связи (CFB) и выходных отзывов (OFB).

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

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

IV

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

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

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

KeySize

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

LegalBlockSizes

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

LegalKeySizes

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

Mode

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

Mode

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

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

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

Padding

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

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

Методы

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

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

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

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

CreateDecryptor(Byte[], Byte[])

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

CreateEncryptor()

Создает симметричный объект шифрования AES с помощью текущего ключа и вектора инициализации (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)

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