Share via


c# cryptographicException Specified key is not a valid size for this algorithm.

Question

Tuesday, September 24, 2013 5:04 PM

Can anyone help me?

When i try encrypt results the error: "Specified key is not a valid size for this algorithm."

Whats wrong?

My code:

private static byte[] bIV = 
        { 0x50, 0x08, 0xF1, 0xDD, 0xDE, 0x3C, 0xF2, 0x18, 0x44, 0x74, 0x19, 0x2C, 0x53, 0x49, 0xAB, 0xBC };
internal static string Encrypt(this string plainText) 
{            
  NameValueCollection section = (NameValueCollection)ConfigurationManager.GetSection("secureAppSettings");            
  string cryptoKey = section["Key"];                      
if (!String.IsNullOrEmpty(plainText))
{                                          
byte[] bKey = Convert.FromBase64String(cryptoKey);
byte[] bText = new UTF8Encoding().GetBytes(plainText);
rijndael.KeySize = 256;
MemoryStream mStream = new MemoryStream();
CryptoStream encryptor = new CryptoStream(
      mStream,
      rijndael.CreateEncryptor(bKey, bIV),
      CryptoStreamMode.Write);

encryptor.Write(bText, 0, bText.Length);
encryptor.FlushFinalBlock();

string cryptText = Convert.ToBase64String(mStream.ToArray());
return String.Format("CRYPT:{0}", cryptText);
}
else{ return plainText;}        
} 

       

All replies (2)

Tuesday, September 24, 2013 5:38 PM âś…Answered

I resolve this problem.

My key was 21 bites and needs 32.

I change a key with 32 bites and works!


Wednesday, September 25, 2013 8:10 AM

Hi RodrigoWaldow,

Welcome to the MSDN forum!

I'm glad to hear that you got it working. Thank you for sharing your solutions & experience here. It will be very beneficial for other community members who have similar questions.

<THE CONTENT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED>
Thanks
MSDN Community Support

Please remember to "Mark as Answer" the responses that resolved your issue. It is a common way to recognize those who have helped you, and makes it easier for other visitors to find the resolution later.