加密音频文件时出现异常

本文关键字:异常 音频 文件 加密 | 更新日期: 2023-09-27 18:02:35

在使用c#加密音频文件时,我得到了一个异常,即"指定的初始化向量(IV)与算法的块大小不匹配"。我使用的是密码学课程提供的Rijndael算法。我应该怎么做来解决这个异常?我的代码如下:

      public void EncryptFile(string inputFile, string outputFile)
      {
        try
        {
            inputFile = textBox_path.Text;
            String password = "keykey";
            UnicodeEncoding UE = new UnicodeEncoding();
            byte[] key = UE.GetBytes(password);
            string cryptFile = outputFile;
            FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);

            RijndaelManaged RMCrypto = new RijndaelManaged();
            CryptoStream cs = new CryptoStream(fsCrypt, RMCrypto.CreateEncryptor(key, key), 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();
            MessageBox.Show("encryption is completed!!");
        }
        catch(Exception e)
        {
            MessageBox.Show(e.Message);
        }
  }

和我的函数调用是:

加密音频文件时出现异常

这里有一个类似的问题。

使用Rijndael,您可以选择块大小128、160、192、224或256位。然后必须选择相同长度的初始化向量:

                using (RijndaelManaged rm = new RijndaelManaged())
                {
                    rm.BlockSize = 128;
                    Rfc2898DeriveBytes keyDerivator = new Rfc2898DeriveBytes(password, salt, KeyGenIterationCount); //derive key and IV from password and salt using the PBKDF2 algorithm
                    rm.IV = keyDerivator.GetBytes(16); //16 bytes (128 bits, same as the block size)
                    rm.Key = keyDerivator.GetBytes(32);
                    //(encrypt here)
                }

在任何情况下,我建议使用AesCryptoServiceProvider类,因为它是fips编译器。点击这里了解更多不同之处:http://blogs.msdn.com/b/shawnfa/archive/2006/10/09/the-differences-between-rijndael-and-aes.aspx