亲爱的社区成员!
帮助改进代码!要加密字符串(需要将机密数据保存到公共数据库),我使用该类:
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 方法。请帮我理解...
提前致谢!!!
非常感谢用户@Kotomi 的回答。他提出了正确的选择,我分享: