我真的不确定这里发生了什么。我的应用程序正在正确加密文件并且没有问题,但是在尝试解密同一文件时抛出了 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 被捕获 Message="Index is outside the bounds of the array."
Source="mscorlib" StackTrace:在 System.Security.Cryptography.RijndaelManagedTransform.DecryptData(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount, Byte[]& outputBuffer, Int32 outputOffset, PaddingMode paddingMode, Boolean fLast) 在 System.Security.Cryptography .RijndaelManagedTransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount) at System.Security.Cryptography.CryptoStream.FlushFinalBlock() at System.Security.Cryptography.CryptoStream.Dispose(Boolean disposing) at System.IO.Stream.Close () 在 D:\Development\Projects\Web\WebSite1\App_Code\Crypt.vb:line 34 InnerException 中的 Crypt.EncryptDecrypt(String Action, String InFile, String OutFile):
任何帮助将不胜感激。
编辑 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="Index is outside the bounds of the array." Source="mscorlib" StackTrace:在 System.Security.Cryptography.RijndaelManagedTransform.DecryptData(Byte[] > inputBuffer, Int32 inputOffset, Int32 inputCount, Byte[]& outputBuffer, Int32 > outputOffset, PaddingMode paddingMode, Boolean fLast) 在 System.Security .Cryptography.RijndaelManagedTransform.TransformFinalBlock(Byte[] > inputBuffer, Int32 inputOffset, Int32 inputCount) 在 System.Security.Cryptography.CryptoStream.FlushFinalBlock() 在 System.Security.Cryptography.CryptoStream.Dispose(Boolean disposing) 在 System.IO。 Stream.Close() at Crypt.EncryptDecrypt(String Action, String InFile, String OutFile) in > D:
在我看来,这是同样的错误......
结束编辑 1