【问题标题】:Aes encryption in .net Core 3.0 'Specified key is not a valid size for this algorithm.'.net Core 3.0 中的 Aes 加密“指定的密钥不是此算法的有效大小。”
【发布时间】:2019-05-24 14:26:01
【问题描述】:

使用 .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.'

我做错了什么?谢谢。

【问题讨论】:

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


【解决方案1】:

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

我建议您在 AES 类中使用 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");

对于 192 位 - 对于 192 位密钥,密钥的长度应为 24 大小样本键将是这样的

mysmallkey12345512987651 

对于 256 位 - 对于 256 位密钥,密钥的长度应为 32 大小样本键

mysmallkey1234551298765134567890

【讨论】:

  • 很高兴为您提供帮助..!
猜你喜欢
  • 2011-02-24
  • 2020-09-25
  • 2010-12-22
  • 1970-01-01
  • 2017-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多