2014-05-10 43 views
-1

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

     } 

    } 

和我的函數調用:

+1

你應該做什麼?那麼,基於錯誤我會說你需要有IV匹配塊的大小。沒有看到你的代碼或更多的信息是關於你會得到的最好的答案,除非有人在這裏可以閱讀頭腦...... – Tim

+0

請張貼您的代碼。 –

+0

[指定的初始化向量(IV)可能與此算法的塊大小不匹配](http://stackoverflow.com/questions/944833/specified-initialization-vector-iv-does-not-match-the-塊大小換這個-ALGO) –

回答

0

有一個類似的問題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-compilant。閱讀更多關於這裏的差異:http://blogs.msdn.com/b/shawnfa/archive/2006/10/09/the-differences-between-rijndael-and-aes.aspx