【发布时间】:2011-02-16 22:16:48
【问题描述】:
我真的不确定这里发生了什么。我的应用程序正在正确加密文件且没有问题,但在尝试解密同一文件时抛出 IndexOutOfRangeException...
这是我的代码:
Public Sub EncryptDecrypt(ByVal Action As String, ByVal InFile As String, ByVal OutFile As String)
Try
Dim Buffer(4096) As Byte
Dim Stream As CryptoStream
Dim Rij As New System.Security.Cryptography.RijndaelManaged
Dim Key(), IV() As Byte
FSIn = New FileStream(InFile, FileMode.Open, FileAccess.Read)
FSOut = New FileStream(OutFile, FileMode.OpenOrCreate, FileAccess.Write)
FSOut.SetLength(0)
Key = CreateKey("p0Ju423KQY7h4D29Ml536jbX7gS2Q6Rtm87XvRttlKiZ")
IV = CreateIV("p0Ju423KQY7h4D29Ml536jbX7gS2Q6Rtm87XvRttlKiZ")
If Action = "E" Then
Stream = New CryptoStream(FSOut, Rij.CreateEncryptor(Key, IV), CryptoStreamMode.Write)
Else
Stream = New CryptoStream(FSOut, Rij.CreateDecryptor(Key, IV), CryptoStreamMode.Write)
End If
Stream.Close()
FSIn.Close()
FSOut.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
错误出现在Stream.Close() 行。
我在其他地方应用了相同的代码,它没有任何问题......
这是我的堆栈跟踪:
System.IndexOutOfRangeException 是 抓到消息="索引在外面 数组的边界。”
来源="mscorlib" 堆栈跟踪: 在 System.Security.Cryptography.RijndaelManagedTransform.DecryptData(字节 [] 输入缓冲区,Int32 输入偏移量,Int32 输入计数,字节 []& 输出缓冲区, Int32 outputOffset, PaddingMode paddingMode, 布尔型 fLast) 在 System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(字节 [] 输入缓冲区,Int32 输入偏移量,Int32 输入计数) 在 System.Security.Cryptography.CryptoStream.FlushFinalBlock() 在 System.Security.Cryptography.CryptoStream.Dispose(布尔 处置) 在 System.IO.Stream.Close() 在 Crypt.EncryptDecrypt(字符串操作,字符串 InFile,字符串 OutFile) 在 D:\Development\Projects\Web\WebSite1\App_Code\Crypt.vb:line 34 内部异常:
任何帮助将不胜感激。
编辑 1 经过aaz的评论,我修改替换了
Stream = New CryptoStream(FSOut, Rij.CreateDecryptor(Key, IV), CryptoStreamMode.Write)
与
Stream = New CryptoStream(FSIn, Rij.CreateDecryptor(Key, IV), CryptoStreamMode.Write)
这是生成的堆栈跟踪:
System.IndexOutOfRangeException 被捕获 Message="索引超出了数组的范围。" 来源="mscorlib" 堆栈跟踪: 在 System.Security.Cryptography.RijndaelManagedTransform.DecryptData(Byte[] > inputBuffer, Int32 inputOffset, Int32 inputCount, Byte[]& outputBuffer, Int32 > outputOffset, PaddingMode paddingMode, Boolean fLast) 在 System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(字节 [] > inputBuffer,Int32 inputOffset,Int32 inputCount) 在 System.Security.Cryptography.CryptoStream.FlushFinalBlock() 在 System.Security.Cryptography.CryptoStream.Dispose(布尔处理) 在 System.IO.Stream.Close() 在 Crypt.EncryptDecrypt(String Action, String InFile, String OutFile) in > D:\Development\Projects\Web\WebSite1\App_Code\Crypt.vb:line 34 内部异常:
在我看来,这是同样的错误......
结束编辑 1
【问题讨论】:
-
代码是否完整?它实际上并没有将数据从
FSIn复制到Stream。 -
这让我感到困惑......它在我使用它的另一个应用程序中完美运行。不过,我对加密还很陌生,所以我只是在这里和那里修修补补。
标签: security encryption filestream rijndaelmanaged