Rijndael key size in C#

user6248151 picture user6248151 · Apr 24, 2016 · Viewed 11.5k times · Source

I'm currently developing a little tool in C# that allows me to quickly crypt my files. So I used this script which looks to be perfect for me. But I still have a problem : the key is too short (8 character max). I read in RijndaelManaged() documentation that maximum size for the key is 256 bits, so I should be able to use a 64 character key... (like sha256 hash)

But every time I try to increase the key size, I get a nice "Encryption failed !", even for 9 characters. I've been looking for a solution on google for a while, but nothing useful.

The best thing I found is this. So I tried to change the padding like:

RMCrypto.Padding = PaddingMode.ISO10126;

// or
RMCrypto.Padding = PaddingMode.ANSIX923;

But it did not change anything...

Answer

Ian picture Ian · Apr 24, 2016

Rjindael's key size is not free to choose. It must be 128-bit, 192-bit, or 256-bit. It cannot be, say, 9 bytes or 18 bytes or 36 bytes. It must strictly be 16 bytes, 24 bytes, or 32 bytes.

Besides, you should first specify your key size suitably before you could use the class correctly. Though both 128-bit and 192-bit key size are allowed, you cannot, for instance, specify the key size to be 128-bit but using 192-bit key. The key size you specify must match the key size you use.

This is an example how you do it:

You could specify your key size (not to be confused with BlockSize) in the RjindaelManaged.KeySize property:

RMCrypto.KeySize = 256;

And then the key size in byte[] should match with the size of the key above:

byte[] key = new byte[]{ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F }; 
RMCrypto.Key = key;

Be sure to use a key that looks like random noise in order to get some security.

Currently your key is too short:

string password = @"myKey123";
byte[] key = UE.GetBytes(password);