Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specified initialization vector (IV) does not match the block size for this algorithm

The problem is your initialization vector size needs to be 16 bytes.

Your initial vector size is 14 bytes.

You will need to increase the size of your initial vector by 2 bytes and your code will work.

Example:

string initVector = "HR$2pIjHR$2pIj12";

You will then get the output with your current code and the example IV (initialization vector) size provided:

hAC8hMf3N5Zb/DZhFKi6Sg==

This article provides a good explanation on what the initialization vector is.

http://en.wikipedia.org/wiki/Initialization_vector


You should be able to check how many bytes the IV needs to be using:

algorithm.BlockSize / 8

BlockSize is in bits, so 128 bits / 8 gives 16 bytes of ASCII, and you may also find Rfc2898DeriveBytes a useful class for producing keys.

algorithm.IV = rfc2898DeriveBytesForIV.GetBytes(algorithm.BlockSize / 8);

Hope it helps.


If someone is migrating their code from .NET framework to .NET Core and starts getting this exception on RijndaelManaged.CreateEncryptor: your old cold was working due to the fact that ".NET Framework allows IVs greater than 64 bits and truncates them".

To resolve see Kevin Jones comment: "simply change your IV to only the first 8 bytes"

So, as an example:

private static byte[] IV_192 =  { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18 };

would become:

// Rename field if desired.
private static byte[] IV_192 =  { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 };

Also worth noting, "Rijndael class is the predecessor of the Aes algorithm. You should use the Aes algorithm instead of Rijndael."