Key
Key у
Aes
принимает 32 байта при
KeySize = 256. Пример ключа -
Encoding.UTF8.GetBytes
строки "12345678901234567890123456789012".
15 байт дают CryptographicException.
Синтаксис
aes.Key = Encoding.UTF8.GetBytes("12345678901234567890123456789012");
Пример
Давайте проверить длину допустимого ключа:
using System;
using System.Security.Cryptography;
using System.Text;
class Program
{
static void Main()
{
byte[] key = Encoding.UTF8.GetBytes(
"12345678901234567890123456789012");
using Aes aes = Aes.Create();
aes.Key = key;
int res = aes.Key.Length;
Console.WriteLine(res);
}
}
Результат выполнения кода:
32
Пример
Давайте поймаем слишком короткий ключ:
using System;
using System.Security.Cryptography;
using System.Text;
class Program
{
static void Main()
{
byte[] badKey = Encoding.UTF8.GetBytes("123456789012345");
try
{
using Aes aes = Aes.Create();
aes.Key = badKey;
}
catch (CryptographicException)
{
Console.WriteLine("fail");
}
}
}
Результат выполнения кода:
"fail"
Пример
Давайте расшифровать после задания ключа:
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"
Смотрите также
-
IV,
начальный вектор -
CreateEncryptor,
шифрование -
CreateDecryptor,
расшифровка -
Aes,
класс AES