Program crashes when setting values in Rijndael class

139 Views Asked by At

I currently have the following code.

I am generating a byte array from a hard coded random string.

Now I noticed that when setting up a Rijndael class the application crashes when setting the key value. Any suggestions on why it crashes when the key value is set.

int olength = 18; 
string HKey = "ABCDEFGHIJKL111100002222"; //Some random string 
byte[] key = Convert.FromBase64String(HardcodedKey); //key.length = 18
byte[] iv = Encryption.GenerateRandomBytes(olength);
CryptoStream cs = Encryption.AES128Stream(key, iv, Context.Response.Body);

Now the above method being called is give below

public static CryptoStream AES128Stream(byte[] key, byte[] iv, Stream stream)
{
    try
    {
        Rijndael rijndael = Rijndael.Create();
        rijndael.Mode = CipherMode.CBC;
        rijndael.Padding = PaddingMode.PKCS7;
        rijndael.KeySize = 128;
        rijndael.BlockSize = 128;
        rijndael.Key = key;  ///---->CRASHES HERE
        rijndael.IV = iv;

        ICryptoTransform rijndaelEncryptor = rijndael.CreateEncryptor();
        return new CryptoStream(stream, rijndaelEncryptor, CryptoStreamMode.Write);
    }
    catch (Exception e)
    {
        throw e;
    }
}

In additional information it states

Additional information: Specified key is not a valid size for this algorithm.

In that case what string can I use that will work ? Why is this string not working ?

1

There are 1 best solutions below

1
On BEST ANSWER

Since you define the Rjindael to be having keysize of 128-bit, you have to give exactly 16 bytes to the class to work. Your key seems to be too long (or too short).

Also, since I cannot know your true key, I do not know if your Convert.FromBase64String() is correctly used or not. But, I suggest you can directly use byte[] to avoid that problem:

//put 16 to be really sure.
byte[] key = new byte[16] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };