2012-01-12 24 views
0

RijndaelManaged Cipherを使用するDecryptString関数があります。それは99.999%の時間で動作しますが、非常に時折、「IndexOutOfRangeException」例外が発生し、「Indexは配列の境界外です」というメッセージが表示されます。 finallyブロックのcryptoStreamをクローズしようとしたとき。CryptoStreamインスタンスが終了したときにスローされる例外

動作が停止すると、動作が20分ほど停止してから、明示的に明示的に動作しないで、 を再度起動します。おそらくあなたはこれらの二つの文を逆にすべきである - 私が持っている一つのリードが、それは私が通知を行うだけで、ST

public string DecryptString(string InputText, string Password) 
     { 
      //checkParamSupplied("InputText", InputText); 
      checkParamSupplied("Password", Password); 

      MemoryStream memoryStream = null; 
      CryptoStream cryptoStream = null; 

      try 
      { 
       RijndaelManaged RijndaelCipher = new RijndaelManaged(); 

       byte[] EncryptedData = Convert.FromBase64String(InputText); 

       byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString()); 

       PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt); 

       // Create a decryptor from the existing SecretKey bytes. 
       ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16)); 

       memoryStream = new MemoryStream(EncryptedData); 

       // Create a CryptoStream. (always use Read mode for decryption). 
       cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read); 

       // Since at this point we don't know what the size of decrypted data 
       // will be, allocate the buffer long enough to hold EncryptedData; 
       // DecryptedData is never longer than EncryptedData. 
       byte[] PlainText = new byte[EncryptedData.Length]; 

       // Start decrypting. 
       int DecryptedCount = cryptoStream.Read(PlainText, 0, PlainText.Length); 

       // Convert decrypted data into a string. 
       string DecryptedData = Encoding.Unicode.GetString(PlainText, 0, DecryptedCount); 

       // Return decrypted string. 
       return DecryptedData; 
      } 
      catch (Exception ex) 
      { 
       throw; 
      } 
      finally 
      { 
       //Close both streams. 
       memoryStream.Close(); 
       cryptoStream.Close(); 
      } 
     } 
+0

ジョナサン - あなたの質問は不完全です... –

+0

テキストとコードの両方が途切れているようです... –

+0

ありがとう、私のブラウザは再生していました。残りのコードを追加しました。 –

答えて

1

ことの一つは、あなたがあなたのfinallyブロックにcryptoStream自体を閉じる前に、あなたはcryptoStreamのストリームを終了していることであるということです?

+1

。ブロックを使用してそれらを(ネストされた)ラップすると、この種の混乱とエラーも防止されます。 –

関連する問題