AesCryptoServiceProvider.CreateEncryptor Метод

Определение

Создает объект-шифратор для алгоритма симметричного шифрования AES.

Перегрузки

CreateEncryptor()

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

CreateEncryptor(Byte[], Byte[])

Создает объект-шифратор для алгоритма симметричного шифрования, используя заданный ключ и вектор инициализации.

CreateEncryptor()

Исходный код:
AesCryptoServiceProvider.cs
Исходный код:
AesCryptoServiceProvider.cs
Исходный код:
AesCryptoServiceProvider.cs

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

public:
 override System::Security::Cryptography::ICryptoTransform ^ CreateEncryptor();
public override System.Security.Cryptography.ICryptoTransform CreateEncryptor ();
[System.Security.SecurityCritical]
public override System.Security.Cryptography.ICryptoTransform CreateEncryptor ();
override this.CreateEncryptor : unit -> System.Security.Cryptography.ICryptoTransform
[<System.Security.SecurityCritical>]
override this.CreateEncryptor : unit -> System.Security.Cryptography.ICryptoTransform
Public Overrides Function CreateEncryptor () As ICryptoTransform

Возвращаемое значение

Симметричный объект-шифратор AES.

Атрибуты

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

CreateEncryptor(Byte[], Byte[])

Исходный код:
AesCryptoServiceProvider.cs
Исходный код:
AesCryptoServiceProvider.cs
Исходный код:
AesCryptoServiceProvider.cs

Создает объект-шифратор для алгоритма симметричного шифрования, используя заданный ключ и вектор инициализации.

public:
 override System::Security::Cryptography::ICryptoTransform ^ CreateEncryptor(cli::array <System::Byte> ^ rgbKey, cli::array <System::Byte> ^ rgbIV);
public:
 override System::Security::Cryptography::ICryptoTransform ^ CreateEncryptor(cli::array <System::Byte> ^ key, cli::array <System::Byte> ^ iv);
public override System.Security.Cryptography.ICryptoTransform CreateEncryptor (byte[] rgbKey, byte[]? rgbIV);
public override System.Security.Cryptography.ICryptoTransform CreateEncryptor (byte[] rgbKey, byte[] rgbIV);
[System.Security.SecurityCritical]
public override System.Security.Cryptography.ICryptoTransform CreateEncryptor (byte[] key, byte[] iv);
public override System.Security.Cryptography.ICryptoTransform CreateEncryptor (byte[] key, byte[] iv);
override this.CreateEncryptor : byte[] * byte[] -> System.Security.Cryptography.ICryptoTransform
[<System.Security.SecurityCritical>]
override this.CreateEncryptor : byte[] * byte[] -> System.Security.Cryptography.ICryptoTransform
Public Overrides Function CreateEncryptor (rgbKey As Byte(), rgbIV As Byte()) As ICryptoTransform
Public Overrides Function CreateEncryptor (key As Byte(), iv As Byte()) As ICryptoTransform

Параметры

rgbKeykey
Byte[]

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

rgbIViv
Byte[]

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

Возвращаемое значение

Симметричный объект-шифратор AES.

Атрибуты

Исключения

Значение параметра key или параметра ivnull.

key недопустим.

Примеры

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

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;
}
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
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()

Комментарии

См. примеры кода в LegalKeySizes свойствах и LegalBlockSizes , чтобы определить размер key параметров и iv .

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