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


I am working on a base encryption method. I am using RijndaelManaged. I got this code from somewhere a long time ago, but can't remember where.

I had my code working before, but something changed and I cannot quite figure it out.

When I run my code, I get the following error;

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

Here is my code:

string textToEncrypt = "TEST STRING";

int keySize = 256;
string hashAlgorithm = "SHA1";
string passPhrase = "AH!PSB0%FGHR$";
string saltValue = "LRT%YUR#VBNL@1";
string initVector = "HR$2pIjHR$2pIj";

byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);

byte[] plainTextBytes = Encoding.UTF8.GetBytes(textToEncrypt);

var password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, 2);

byte[] keyBytes = password.GetBytes(keySize / 8);

RijndaelManaged symmetricKey = new RijndaelManaged();

symmetricKey.Mode = CipherMode.CBC;

ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes,initVectorBytes);

MemoryStream memoryStream = new MemoryStream();

var cryptoStream = new CryptoStream(memoryStream,encryptor,CryptoStreamMode.Write);
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);


byte[] cipherTextBytes = memoryStream.ToArray();


string cipherText = Convert.ToBase64String(cipherTextBytes);

Any help will be appreciated.

Best Solution

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.


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

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


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