CreateEncryptor
CreateEncryptor у
Aes
принимает ключ и IV.
TransformFinalBlock шифрует
"abcde"; расшифровка тем же
ключом и IV через
CreateDecryptor
возвращает исходный текст.
Синтаксис
ICryptoTransform encryptor = aes.CreateEncryptor(key, iv);
byte[] cipher = encryptor.TransformFinalBlock(plain, 0, plain.Length);
Пример
Давайте пройти полный круг шифрования:
using System;
using System.Security.Cryptography;
using System.Text;
class Program
{
static void Main()
{
byte[] key = Encoding.UTF8.GetBytes(
"12345678901234567890123456789012");
byte[] iv = Encoding.UTF8.GetBytes("1234567890123456");
byte[] plain = Encoding.UTF8.GetBytes("abcde");
using Aes aes = Aes.Create();
byte[] cipher = aes.CreateEncryptor(key, iv)
.TransformFinalBlock(plain, 0, plain.Length);
byte[] decoded = aes.CreateDecryptor(key, iv)
.TransformFinalBlock(cipher, 0, cipher.Length);
string res = Encoding.UTF8.GetString(decoded);
Console.WriteLine(res);
}
}
Результат выполнения кода:
"abcde"
Пример
Давайте использовать свойства Key и IV:
using System;
using System.Security.Cryptography;
using System.Text;
class Program
{
static void Main()
{
byte[] key = Encoding.UTF8.GetBytes(
"12345678901234567890123456789012");
byte[] iv = Encoding.UTF8.GetBytes("1234567890123456");
byte[] plain = Encoding.UTF8.GetBytes("abcde");
using Aes aes = Aes.Create();
aes.Key = key;
aes.IV = iv;
byte[] cipher = aes.CreateEncryptor()
.TransformFinalBlock(plain, 0, plain.Length);
byte[] decoded = aes.CreateDecryptor()
.TransformFinalBlock(cipher, 0, cipher.Length);
string res = Encoding.UTF8.GetString(decoded);
Console.WriteLine(res);
}
}
Результат выполнения кода:
"abcde"
Пример
Давайте проверить, что шифр меняет длину блока:
using System;
using System.Security.Cryptography;
using System.Text;
class Program
{
static void Main()
{
byte[] key = Encoding.UTF8.GetBytes(
"12345678901234567890123456789012");
byte[] iv = Encoding.UTF8.GetBytes("1234567890123456");
byte[] plain = Encoding.UTF8.GetBytes("abcde");
using Aes aes = Aes.Create();
byte[] cipher = aes.CreateEncryptor(key, iv)
.TransformFinalBlock(plain, 0, plain.Length);
bool res = cipher.Length != plain.Length;
Console.WriteLine(res);
}
}
Результат выполнения кода:
True
Смотрите также
-
CreateDecryptor,
расшифровка -
Key,
ключ -
IV,
вектор IV -
CryptoStream,
поток шифра