Aes encryption in .net Core 3.0 'Specified key is not a valid size for this algorithm.'
使用.Net Core 3.0,我想使用任何密码长度作为加密密钥来加密一些文本:
1 2 3 4 5 | using (Aes myAes = Aes.Create()) { var key = Encoding.UTF8.GetBytes("mysmallkey"); myAes.Key = key; //ERROR } |
我收到一个错误:
1 | System.Security.Cryptography.CryptographicException: 'Specified key is not a valid size for this algorithm.' |
我究竟做错了什么? 谢谢。
您在这里做错了-
在此处参考文档Aes类
和AES文档
我建议您通过在AES类中使用
1 | public virtual KeySizes[] LegalKeySizes { get; } |
您将获得以下输出
1 2 3 4 5 6 7 8 9 10 11 | 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 } |
如果您使用的是
试试这个
1 | 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
1 | mysmallkey12345512987651 |
For 256 bit - Length of the secret key should be 32 for 256 bits key
size sample key
1 | mysmallkey1234551298765134567890 |