.Net 6.0: "AesManaged" является устаревшим: 'Derived cryptographic types are obsolete. Use the Create method on the base type instead.'
Уважаемые участники сообщества!
Помогите улучшить код! Для шифрования строк (нужно для сохранения конфиденциальных данных в общую базу данных) использую класс:
public static class StringEncriptor
{
private static readonly byte[] KEY = Enumerable.Range(0, 32).Select(x => (byte)x).ToArray();
public static string Encrypt (string text)
{
using AesManaged aes = new() { Key = KEY };
using MemoryStream ms = new();
ms.Write(aes.IV);
using (CryptoStream cs = new(ms, aes.CreateEncryptor(), CryptoStreamMode.Write, true))
{
cs.Write(Encoding.UTF8.GetBytes(text));
}
return Convert.ToBase64String(ms.ToArray());
}
public static string Decrypt (string base64)
{
using MemoryStream ms = new(Convert.FromBase64String(base64));
byte[] iv = new byte[16];
ms.Read(iv);
using AesManaged aes = new() { Key = KEY, IV = iv };
using CryptoStream cs = new(ms, aes.CreateDecryptor(), CryptoStreamMode.Read, true);
using MemoryStream output = new();
cs.CopyTo(output);
return Encoding.UTF8.GetString(output.ToArray());
}
}
Он нормально отрабатывал и полностью выполнял свои функции в .Net 5.0. С релизом .Net 6.0 решил перейти на него (проект ещё в ранней стадии, поэтому вполне реально). И вот столкнулся с таким предупреждением:
SYSLIB0021 "AesManaged" является устаревшим: 'Derived cryptographic types are obsolete. Use the Create method on the base type instead.'
Понятное дело, что надо использовать метод Create родителя. Помогите, пожалуйста разобраться...
Заранее спасибо!!!
Ответы (1 шт):
Автор решения: GoodBoyAlex
→ Ссылка
Спасибо большое пользователю @Kotomi за ответ. Он предложил правильный вариант, которым я делюсь:
public static class StringEncriptor
{
private static readonly byte[] KEY = Enumerable.Range(0, 32).Select(x => (byte)x).ToArray();
public static string Encrypt (string text)
{
using Aes aes = Aes.Create("AesManaged");
aes.Key = KEY;
using MemoryStream ms = new();
ms.Write(aes.IV);
using (CryptoStream cs = new(ms, aes.CreateEncryptor(), CryptoStreamMode.Write, true))
{
cs.Write(Encoding.UTF8.GetBytes(text));
}
return Convert.ToBase64String(ms.ToArray());
}
public static string Decrypt (string base64)
{
using MemoryStream ms = new(Convert.FromBase64String(base64));
byte[] iv = new byte[16];
ms.Read(iv);
using Aes aes = Aes.Create("AesManaged");
aes.Key = KEY;
aes.IV = iv;
using CryptoStream cs = new(ms, aes.CreateDecryptor(), CryptoStreamMode.Read, true);
using MemoryStream output = new();
cs.CopyTo(output);
return Encoding.UTF8.GetString(output.ToArray());
}
}