views:

2789

answers:

1

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 algorithm.

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);

            PasswordDeriveBytes 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();

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

            cryptoStream.FlushFinalBlock();

            byte[] cipherTextBytes = memoryStream.ToArray();

            memoryStream.Close();
            cryptoStream.Close();

            string cipherText = Convert.ToBase64String(cipherTextBytes);

Any help will be appreciated.

+7  A: 

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

Jason Heine
Oh my, this was it! Thank you so much for the help.