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

Aes encryption in .net Core 3.0 'Specified key is not a valid size for this algorithm.'

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

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 ClassAES Documentation

我建议您在 AES class 中使用 LegalKeySizes property,您可以检查密钥的有效大小。有效密钥大小由特定的对称算法实现指定,并列在 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