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