I am needing some help with AES encryption/decryption in C#. Specifically, I want to generate an IV with RijndaelManaged, convert it to text, and store the IV with the encrypted text in the database. I want to append the IV to the beginning of the encrypted data so I can remove it and use it for decryption functions.
Here is where my confusion is... The IV generated by RijndaelManaged is a byte array, 16 bytes long. So I'm thinking that the IV should be 16 characters long when converted to text but that's not what's happening.
The IV is 16 bytes in length, but when I convert those 16 bytes to text, it is 24 characters long. Is that normal somehow? Is that going to happen every time? If so then I will just take the first 24 characters of the encrypted text as the IV for decryption instead of the first 16 character (but that creates another error as described below). I would really like to understand what is going on.
Here the some code.
RijndaelManaged RM= new RijndaelManaged();
byte[] InitialVectorBytes = RM.IV;
// For testing
string stringIV = Convert.ToBase64String(InitialVectorBytes);
int IVLength = InitialVectorBytes.Length;
string test = "IV is " + stringIV + ". Length is " + IVLength;
MessageBox.Show(test);
// MessageBox displays - "IV is m4L5Xs2FsPoIMSH7qraghQ==. Length is 16"
So the IV is 24 characters long (and always ends in == for some reason) but the IV lengths is 16. I've only tested this a few times but that seems to be the pattern.
There is a problem when I do grab the first 24 character from the encrypted text as the IV then decrypt with it...
//Using the first 24 characters of encrypted text as the IV
string InitialVector = CipherText.Remove(24);
byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
ICryptoTransform Decryptor = RM.CreateDecryptor(KeyBytes, InitialVectorBytes)
I get another error... "Specified initialization vector (IV) does not match the block size for this algorithm."
Thanks in advance. Any help would be appreciated.