c# - .net Core 3.0 'Specified key is not a valid size for this algorithm.' 中的 Aes 加密

标签 c# .net .net-core-3.0

使用 .Net Core 3.0 我想加密一些文本,使用任何密码长度作为加密 key :

using (Aes myAes = Aes.Create())
{
   var key = Encoding.UTF8.GetBytes("mysmallkey");
   myAes.Key = key; //ERROR
}

我收到一个错误:
System.Security.Cryptography.CryptographicException: 'Specified key is not a valid size for this algorithm.'

我究竟做错了什么?谢谢。

最佳答案

你在这里做错了 - var key = Encoding.UTF8.GetBytes("mysmallkey"); Refer Documentation here Aes Class
AES Documentation

我建议您通过在 AES 类中使用 LegalKeySizes property 来检查 key 的有效大小。有效的 key 大小由特定的对称算法实现指定,并在 LegalKeySizes 属性中列出。

 public virtual KeySizes[] LegalKeySizes { get; }

您将获得以下输出
var key = Encoding.UTF8.GetBytes("mysmallkey");
  //myAes.Key = Key; //ERROR
   KeySizes[] ks = myAes.LegalKeySizes;
   foreach (KeySizes item in ks)
   {
    Console.WriteLine("Legal min key size = " + item.MinSize);
    Console.WriteLine("Legal max key size = " + item.MaxSize);
    //Output
    // Legal min key size = 128
    // Legal max key size = 256
   }

如果您使用的是 128 bit then Length of secret key should be 16 for 128 bits key size 试试这个
 var key = Encoding.UTF8.GetBytes("mysmallkey123456");

For 192 bit - Length of the secret key should be 24 for 192 bits key size sample key will be like this


mysmallkey12345512987651 

For 256 bit - Length of the secret key should be 32 for 256 bits key size sample key


mysmallkey1234551298765134567890

关于c# - .net Core 3.0 'Specified key is not a valid size for this algorithm.' 中的 Aes 加密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56294646/

相关文章:

asp.net - Microsoft 是否推荐方法或查询语法?

c# - 将类转换为 XML 到字符串

c# - 数据表到数据集xsd?

c# - 扩展扩展方法?或者其他的东西?

c# - 在单词互操作中使用选择和范围

c# - 模拟 System.Net.FtpClient GetHash 方法

json - .Net Core 3 和 EF Core 3 包含问题 (JsonException)

asp.net - 如何在.NET Core 3.0 Preview 9中正确实现JsonPatch?

c# - 通过反射获取当前的MethodBase

c# - 非常慢的性能结构