System.Security.Cryptography.CryptographicException未处理

时间:2015-12-10 08:29:04

标签: vb.net encryption cryptography

我正在使用以下代码来加密和解密文件:

<DllImport("kernel32.dll")> _
Public Shared Sub ZeroMemory(ByVal addr As IntPtr, ByVal size As Integer)
End Sub
Public Function GenerateKey() As String
    ' Create an instance of a symmetric algorithm. The key and the IV are generated automatically.
    Dim desCrypto As DESCryptoServiceProvider = DESCryptoServiceProvider.Create()

    ' Use the automatically generated key for encryption. 
    Return ASCIIEncoding.ASCII.GetString(desCrypto.Key)

End Function
Sub EncryptFile(ByVal sInputFilename As String, _
              ByVal sOutputFilename As String, _
              ByVal sKey As String)

    Dim fsInput As New FileStream(sInputFilename, _
                                FileMode.Open, FileAccess.Read)
    Dim fsEncrypted As New FileStream(sOutputFilename, _
                                FileMode.Create, FileAccess.Write)

    Dim DES As New DESCryptoServiceProvider()

    'Set secret key for DES algorithm.
    'A 64-bit key and an IV are required for this provider.
    DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey)

    'Set the initialization vector.
    DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey)

    'Create the DES encryptor from this instance.
    Dim desencrypt As ICryptoTransform = DES.CreateEncryptor()
    'Create the crypto stream that transforms the file stream by using DES encryption.
    Dim cryptostream As New CryptoStream(fsEncrypted, _
                                        desencrypt, _
                                        CryptoStreamMode.Write)

    'Read the file text to the byte array.
    Dim bytearrayinput(fsInput.Length - 1) As Byte
    fsInput.Read(bytearrayinput, 0, bytearrayinput.Length)
    'Write out the DES encrypted file.
    cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length)
    cryptostream.Close()
End Sub
Sub DecryptFile(ByVal sInputFilename As String, _
   ByVal sOutputFilename As String, _
   ByVal sKey As String)

    Dim DES As New DESCryptoServiceProvider()
    'A 64-bit key and an IV are required for this provider.
    'Set the secret key for the DES algorithm.
    DES.Key() = ASCIIEncoding.ASCII.GetBytes(sKey)
    'Set the initialization vector.
    DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey)

    'Create the file stream to read the encrypted file back.
    Dim fsread As New FileStream(sInputFilename, FileMode.Open, FileAccess.Read)
    'Create the DES decryptor from the DES instance.
    Dim desdecrypt As ICryptoTransform = DES.CreateDecryptor()
    'Create the crypto stream set to read and to do a DES decryption transform on incoming bytes.
    Dim cryptostreamDecr As New CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read)
    'Print out the contents of the decrypted file.
    Dim fsDecrypted As New StreamWriter(sOutputFilename)
    fsDecrypted.Write(New StreamReader(cryptostreamDecr).ReadToEnd)
    fsDecrypted.Flush()
    fsDecrypted.Close()
End Sub

函数被称为:

Sub main()
    Dim sSecretKey As String
    Dim c As New Crpt.Crpt
    Dim fTest As FileStream = File.Create("d:\GKey.txt")
    sSecretKey = c.GenerateKey()
    Dim info As Byte() = New UTF8Encoding(True).GetBytes(sSecretKey)
    fTest.Write(info, 0, info.Length)
    fTest.Close()
    'Console.WriteLine(sSecretKey)
    'Console.Read()
    Dim gch As GCHandle = GCHandle.Alloc(sSecretKey, GCHandleType.Pinned)
    c.EncryptFile("d:\test.txt", AppDomain.CurrentDomain.BaseDirectory.ToString() + "\NRS.lic", sSecretKey)
    ZeroMemory(gch.AddrOfPinnedObject(), sSecretKey.Length * 2)
    gch.Free()
End Sub

以上在本子主题中我将test.txt文件加密为NRS.lic

我正在尝试使用以下方法解密它:

Public Sub dcrpt()
    Dim C As New Crpt.Crpt
    Dim sKey As String
    sKey = "???:8w?"
    Dim gch As GCHandle = GCHandle.Alloc(sKey, GCHandleType.Pinned)
    'C.DecryptFile(AppDomain.CurrentDomain.BaseDirectory.ToString() + "NRS.lic", "c:\Nrs.txt", "??5\????")
    C.DecryptFile(AppDomain.CurrentDomain.BaseDirectory.ToString() + "\NRS.lic", "d:\Nrs.txt", sKey)
    ZeroMemory(gch.AddrOfPinnedObject(), sKey.Length * 2)
    gch.Free()
End Sub

我得到一个例外:

  

System.Security.Cryptography.CryptographicException未处理   HResult = -2146893819消息=错误数据。

完整的堆栈跟踪是:

  

堆栈跟踪:          在System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32)   小时)          在System.Security.Cryptography.Utils._DecryptData(SafeKeyHandle hKey,   字节[]数据,Int32 ib,Int32 cb,字节[]&amp; outputBuffer,Int32   outputOffset,PaddingMode PaddingMode,Boolean fDone)          在System.Security.Cryptography.CryptoAPITransform.TransformFinalBlock(Byte []   inputBuffer,Int32 inputOffset,Int32 inputCount)          在System.Security.Cryptography.CryptoStream.Read(Byte []缓冲区,Int32偏移量,Int32计数)          在System.IO.StreamReader.ReadBuffer()          在System.IO.StreamReader.ReadToEnd()          at Crpt.Crpt.DecryptFile(String sInputFilename,String sOutputFilename,String sKey)in   d:\ NRS \ NikRosterScheduler \ Crpt \ Crpt.vb:第70行          在NikRosterScheduler.frmMDI.dcrpt()的d:\ NRS \ NikRosterScheduler \ NikRosterScheduler \ frmMDI.vb:第17行          在NikRosterScheduler.frmMDI.frmMDI_Load(Object sender,EventArgs e)中   d:\ NRS \ NikRosterScheduler \ NikRosterScheduler \ frmMDI.vb:第60行          在System.EventHandler.Invoke(Object sender,EventArgs e)          在System.Windows.Forms.Form.OnLoad(EventArgs e)          在System.Windows.Forms.Form.OnCreateControl()          在System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)          在System.Windows.Forms.Control.CreateControl()          在System.Windows.Forms.Control.WmShowWindow(消息&amp; m)          在System.Windows.Forms.Control.WndProc(消息&amp; m)          在System.Windows.Forms.ScrollableControl.WndProc(消息&amp; m)          在System.Windows.Forms.ContainerControl.WndProc(消息&amp; m)          在System.Windows.Forms.Form.WmShowWindow(消息&amp; m)          在System.Windows.Forms.Form.WndProc(消息&amp; m)          在System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message&amp; m)          在System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&amp; m)          在System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd,Int32 msg,IntPtr wparam,IntPtr lparam)          在System.Windows.Forms.UnsafeNativeMethods.SendMessage(HandleRef hWnd,   Int32 msg,Int32 wParam,Int32 lParam)          在System.Windows.Forms.Form.SetVisibleCore(布尔值)          在System.Windows.Forms.Control.set_Visible(布尔值)          在System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32)   原因,ApplicationContext上下文)          在System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32)   原因,ApplicationContext上下文)          在System.Windows.Forms.Application.Run(ApplicationContext context)          在Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()          在Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()          在Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String []   命令行)          在NikRosterScheduler.My.MyApplication.Main(String [] Args)in 17d14f5c-a337-4978-8281-53493378c1071.vb:第81行          在System.AppDomain._nExecuteAssembly(RuntimeAssembly程序集,String [] args)          在System.AppDomain.ExecuteAssembly(String assemblyFile,Evidence assemblySecurity,String [] args)          在Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()          在System.Threading.ThreadHelper.ThreadStart_Context(对象状态)          在System.Threading.ExecutionContext.RunInternal(ExecutionContext   executionContext,ContextCallback回调,对象状态,布尔值   preserveSyncCtx)          at System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback callback,Object state,Boolean   preserveSyncCtx)          在System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback回调,对象状态)          在System.Threading.ThreadHelper.ThreadStart()InnerException:

注意:

当我尝试解密文件时,我在上面加密它使用没有错误,它工作正常:

c.EncryptFile("d:\test.txt", AppDomain.CurrentDomain.BaseDirectory.ToString() + "\NRS.lic", sSecretKey)
    c.DecryptFile(AppDomain.CurrentDomain.BaseDirectory.ToString() + "\NRS.lic", "d:\nrs.txt", sSecretKey)

请帮忙

0 个答案:

没有答案