Search code examples
c#encryptionrijndaelmanaged

IV Block Size Issue with RijndaelManaged in C#



I am having trouble with this code to encrypt a string using RinjndaelManaged. I kept getting the error "Specified initialization vector (IV) does not match the block size for this algorithm" and have matched the key and IV length and tried a 32 char length for they key and every 4 bytes from 4 to 32. The code errors at the line starting with:

aes.IV = Convert.FromBase64String(myString);

The code block is as follows:

private String AES_encrypt(String Input)
    {
        var aes = new RijndaelManaged();
        aes.KeySize = 256;
        aes.BlockSize = 256;
        aes.Padding = PaddingMode.PKCS7;
        String myString = new string('J', 32);
        aes.Key = Convert.FromBase64String(myString);
        aes.IV = Convert.FromBase64String(myString);
        var encrypt = aes.CreateEncryptor(aes.Key, aes.IV);
        byte[] xBuff = null;
        using (var ms = new MemoryStream())
        {
            using (var cs = new CryptoStream(ms, encrypt, CryptoStreamMode.Write))
            {
                byte[] xXml = Encoding.UTF8.GetBytes(Input);
                cs.Write(xXml, 0, xXml.Length);
            }

            xBuff = ms.ToArray();
        }

        String Output = Convert.ToBase64String(xBuff);
        return Output;
    }
}

I only used the myString length to just to quickly iterate through a bunch of options. I'm using this particular Keysize/Block/Padding and encryption scheme to work with PHP code which would decrypt this data.


Solution

  • A string of 32 'J's will produce 24 bytes, not 16 or 32. Do not try to Base64 decode it. Best to read-up on Base64.

    It is not secure to use the same value for the key and IV.