【问题标题】:Exception while encrypting audio file加密音频文件时出现异常
【发布时间】:2014-05-10 07:35:42
【问题描述】:

在使用 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);

        }

  }

我的函数调用是:

【问题讨论】:

标签: c#


【解决方案1】:

有一个类似的问题here

使用 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多