CreateDecryptor
CreateDecryptor у
Aes
нужен тот же ключ и IV, что при
CreateEncryptor.
Иначе строка не равна "abcde"
или бросается CryptographicException.
Синтаксис
ICryptoTransform decryptor = aes.CreateDecryptor(key, iv);
byte[] plain = decryptor.TransformFinalBlock(cipher, 0, cipher.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"
Пример
Давайте расшифровать с другим IV. Дополнение PKCS7 не сходится:
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[] wrongIv = Encoding.UTF8.GetBytes("0000000000000000");
byte[] plain = Encoding.UTF8.GetBytes("abcde");
byte[] cipher;
using (Aes aes = Aes.Create())
{
cipher = aes.CreateEncryptor(key, iv)
.TransformFinalBlock(plain, 0, plain.Length);
}
try
{
using Aes aes = Aes.Create();
aes.CreateDecryptor(key, wrongIv)
.TransformFinalBlock(cipher, 0, cipher.Length);
Console.WriteLine("ok");
}
catch (CryptographicException)
{
Console.WriteLine("fail");
}
}
}
Результат выполнения кода:
"fail"
Пример
Давайте расшифровать через свойства AES:
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");
byte[] cipher;
using (Aes aes = Aes.Create())
{
aes.Key = key;
aes.IV = iv;
cipher = aes.CreateEncryptor()
.TransformFinalBlock(plain, 0, plain.Length);
}
using Aes aes = Aes.Create();
aes.Key = key;
aes.IV = iv;
byte[] decoded = aes.CreateDecryptor()
.TransformFinalBlock(cipher, 0, cipher.Length);
string res = Encoding.UTF8.GetString(decoded);
Console.WriteLine(res);
}
}
Результат выполнения кода:
"abcde"
Смотрите также
-
CreateEncryptor,
шифрование -
IV,
начальный вектор -
CryptoStream,
поток шифра -
Aes,
класс AES