简体   繁体   中英

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

I'm trying to make an encryption system with c#. This is the code for the encryption.

public static void EncryptFile(string inFile, string outFile, string @inkey)
    {
        try
        {
            UnicodeEncoding ue = new UnicodeEncoding();
            byte[] key = ue.GetBytes(inkey);
            FileStream fsEncrypt = new FileStream(outFile, FileMode.Create);

            RijndaelManaged rmCrypto = new RijndaelManaged();

            CryptoStream cs = new CryptoStream(fsEncrypt, rmCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write);
            FileStream fsIn = new FileStream(inFile, FileMode.Open);

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

            fsIn.Close(); cs.Close(); fsEncrypt.Close();
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message, "Fail to encrypt", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

Now, this code throws exception every time I run it, says

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

I have read on other discussion about this, saying that there is a problem with the number of bytes (my key length passed into this function is 255). But I have tried making the key only 16 bytes and still not working.

After some troubleshooting I found out that this part:

CryptoStream cs = new CryptoStream(fsEncrypt, rmCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write);

throws the exception. I have no idea why. Anyone can help?

You're passing the key twice to CreateEncryptor , but it needs a key and an IV ( Initialization Vector ). The second parameter should be an array with 128 random bits. 128 bits is the default block size for RijndaelManaged, but it accepts other values as well (such as 256). Read this for more info. And as Grzegorz W pointed out in the comments, you might need to choose a different key size as well.

If you're not familiar with encryption (in which case you should stop and learn more about it before implementing your own solution, or use a ready-made one instead), the function of the IV is prevent that the same message encoded twice produce the same ciphertext. It should be random for each message (and each use of the message), does not need to be kept secret, but you need to store it to be able to decipher the message later (ie you can not discard it after encryption).

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