Click here to Skip to main content
15,888,330 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Following function acceptes encryptedData as in encrypted format
and error occures in Finally block at cs.close Statement.

.Net framework used :3.5.1

Please help.


Error:
The runtime has encountered a fatal error. The address of the error was at 0x7fa7a3ab, on thread 0xbb0. ?The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable?portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke,which may corrupt the stack.


Fuction:

VB
Imports System.Security.Cryptography

Public Function Decrypt(ByVal encryptedData As Data) As Data
    Try
        Dim ms As New System.IO.MemoryStream(encryptedData.Bytes, 0,encryptedData.Bytes.Length)
        Dim b() As Byte = New Byte(encryptedData.Bytes.Length - 1) {}
        ValidateKeyAndIv(False)
        Dim cs As New CryptoStream(ms, _crypto.CreateDecryptor(), CryptoStreamMode.Read)
        Try
            cs.Read(b, 0, encryptedData.Bytes.Length - 1)
        Catch ex As CryptographicException
            Throw New CryptographicException("Unable to decrypt data. The provided key may be invalid.", ex)
        Finally                  
            cs.Close()           
        End Try
        Return New Data(b)
    Catch ex As Exception
        clsLogging.WriteToFileLog(sErrLogFileNM, ex.Message, ex.StackTrace, "")
    End Try 
End Function
Posted
Updated 30-Jul-12 4:52am
v4

1 solution

There are pieces of information missing from your code snippet, namely, the implementation of "ValidateKeyAndIv" and what "_crypto" is and how it was created and setup.

Your inner Try is not needed at all and I'd work on using more meaningful variable names. The days of one letter variables are long gone. Also, the name "Data" is a terrible type name. You may want to call it something more meaningful.

I'd probably rewrite this little piece of code to read:
' Validate encryptedData is an actual instance first, then
' make sure it contains usable data here.
If ... Then
End If

' Allocate a buffer to hold decrypted data
Dim buffer(encryptedData.Length - 1) As Byte

Try
    Using sourceStream As New MemoryStream(encryptedData.Bytes, 0, encryptedData.Bytes.Length - 1)
        Using cryptStream As New CryptoStream(sourceStream, Nothing, CryptoStreamMode.Read)
            cryptStream.Read(buffer, 0, encryptedData.Bytes.Length - 1)
        End Using
    End Using
Catch ex As Exception
    clsLogging.WriteToFileLog(sErrLogFileNM, ex.Message, ex.StackTrace, "")
Finally
    Return New Data(buffer)
End Try
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900