简体   繁体   中英

C# Rijndael IV size doesn't match block size, while it should

I have the following code:

private void EncryptFile(string inputFile, string outputFile, string pass)
    {
        try
        {
            string password = @pass;
            UnicodeEncoding UE = new UnicodeEncoding();
            byte[] key = UE.GetBytes(password);
            byte[] iv = new byte[128];
            for(int i =0; i < iv.Length; i++)
            {
                iv[i] = Convert.ToByte(true);
            }
            string cryptFile = outputFile;
            FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);

            RijndaelManaged RMCrypto = new RijndaelManaged();
            MessageBox.Show(RMCrypto.BlockSize + "\n" + iv.Length);
            CryptoStream cs = new CryptoStream(fsCrypt,
                RMCrypto.CreateEncryptor(key, iv),
                CryptoStreamMode.Write);

            FileStream fsIn = new FileStream(inputFile, FileMode.Open);

            int data;
            while ((data = fsIn.ReadByte()) != -1)
                cs.WriteByte((byte)data);


            fsIn.Close();
            cs.Close();
            fsCrypt.Close();
        }
        catch(Exception ex)
        {
            //MessageBox.Show("Encryption failed!", "Error");
            MessageBox.Show(ex.Message);
        }
    }

But have a problem with the IV size. Using a simple message box I found that (probably) the block size is 128. So, I set the IV to a 128 bytes array full of "1" values to test. The first message box confirms the blocksize and the IV array length are both 128. However, I get an exception saying Specified initialization vector (IV) does not match the block size for this algorithm.

Why is this and how to fix the issue?

AES block size is 128 bits . Not bytes. Bits.

The winner of the AES contest, Rijndael, supports block and key sizes of 128, 192, and 256 bits , but in AES the block size is always 128 bits . The extra block sizes were not adopted by the AES standard

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM