首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >CryptoStream实例关闭时抛出异常

CryptoStream实例关闭时抛出异常
EN

Stack Overflow用户
提问于 2012-01-12 18:01:25
回答 1查看 1.7K关注 0票数 0

我有一个使用RijndaelManaged密码的DecryptString函数。它工作99.999%的时间,但非常偶然的是,它抛出了一个"IndexOutOfRangeException“异常,消息是”索引超出了数组的界限“。当它尝试关闭finally块中的cryptoStream时。

当它停止工作时,它会停止工作20分钟左右,然后在没有明显解释的情况下重新开始工作。我确实有一个线索,那就是它只

代码语言:javascript
复制
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();
            }
        }
EN

回答 1

Stack Overflow用户

发布于 2012-01-12 18:24:13

我确实注意到的一件事是,在关闭finally块中的cryptoStream本身之前,您正在关闭密码流的底层流-也许您应该颠倒这两个语句?

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8833157

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档