Using .Net Core 3.0 I want to encrypt some text, using any password length as an encryption key:
using (Aes myAes = Aes.Create())
{
var key = Encoding.UTF8.GetBytes("mysmallkey");
myAes.Key = key; //ERROR
}
I get an error:
System.Security.Cryptography.CryptographicException: 'Specified key is not a valid size for this algorithm.'
What am I doing wrong? Thanks.
You did wrong here- var key = Encoding.UTF8.GetBytes("mysmallkey");
Refer Documentation here Aes Class
and AES Documentation
I suggest you by using LegalKeySizes property
in AES class you can check the valid size of your key. The valid key sizes are specified by the particular symmetric algorithm implementation and are listed in the LegalKeySizes property.
public virtual KeySizes[] LegalKeySizes { get; }
You will get the below output
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
}
if you are using 128 bit then Length of secret key should be 16 for 128 bits key size
Try this one
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