Results 1 to 7 of 7

Thread: CryptographicException : Access violation

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Aug 2016
    Posts
    69

    CryptographicException : Access violation

    Good day to all,

    I am creating a Class with MD5 encryption/decryption functions to encrypt/decrypt a user password which will be stored in a txt file.

    https://www.youtube.com/watch?v=jhkCoeshpOA

    Encrypt function seems to be working, but the decrypt function is having exceptions.

    The program will first read the encrypted password from text file, use Decrypt function to decrypt with a keyword.


    The Encryption Class
    Code:
    Imports System.Security.Cryptography
    Imports System.Text
    
    Public Class encryption
    
        Dim DES As New TripleDESCryptoServiceProvider
        Dim MD5 As New MD5CryptoServiceProvider
    
        Public Function MD5Hash(value As String) As Byte()
    
            Return MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(value))
        End Function
    
        Public Function Encrypt(StringInput As String, key As String) As String
    
            DES.Key = MD5Hash(key)
            DES.Mode = CipherMode.ECB
    
            Dim buffer As Byte() = ASCIIEncoding.ASCII.GetBytes(StringInput)
    
            Return Convert.ToBase64String(DES.CreateEncryptor().TransformFinalBlock(buffer, 0, buffer.Length))
        End Function
    
        Public Function Decrypt(EncryptedString As String, key As String) As String
    
            DES.Key = MD5Hash(key)
            DES.Mode = CipherMode.ECB
    
            Dim Buffer As Byte() = Convert.FromBase64String(EncryptedString)
    
            Return ASCIIEncoding.ASCII.GetString(DES.CreateDecryptor().TransformFinalBlock(Buffer, 0, Buffer.Length))
        End Function
    
    End Class

    The Login Form
    Code:
    Public Class AdminLoginForm
    
        Private Sub AdminLoginForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            TextBox1.Focus()
    
            'Read user.txt and load values into Settings
            Dim FileToString As String = ""     'grab 1 line from file
            Dim settingString(3) As String      'Store Substring from file to temp String()
            Dim i As Integer = 0                'Array index
            Dim filePath As String = ".\config\user.txt"
            Dim filenum As Integer
    
            filenum = FreeFile()
    
            'Read from File
            Try
                FileOpen(filenum, filePath, OpenMode.Input)
                While Not EOF(filenum)
                    FileToString = LineInput(filenum)               
                    settingString(i) = FileToString
                    i += 1
                End While
    
                FileClose(filenum)
            Catch ex As Exception
                MessageBox.Show("File Error Occurred!" + vbCrLf + ex.ToString)
            End Try
            
            'Decrpyt Password
            Dim decryptedPW As String = ""
            Dim objDecrypt As encryption = New encryption
            decryptedPW = objDecrypt.Decrypt(settingString(1), "EVC")
    
            
            My.Settings.Username = settingString(0)
            My.Settings.Password = decryptedPW
            My.Settings.Save()
    
        End Sub
    ...

    When the Form load, and Access Violation Error occurs.
    Code:
    A first chance exception of type 'System.Security.Cryptography.CryptographicException' occurred in mscorlib.dll
    The program '[13260] EVC_Kiosk_v1.1.vshost.exe: Managed (v4.0.30319)' has exited with code -1073741819 (0xc0000005) 'Access violation'.
    I read somewhere that Access Violation might be due to bad pointer, but I am not sure if that's the case here.
    Any help?

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: CryptographicException : Access violation

    Quote Originally Posted by Volkof View Post
    I am creating a Class with MD5 encryption/decryption functions to encrypt/decrypt a user password which will be stored in a txt file.
    Um, no you're not. MD5 is a hash algorithm. Hashing is, by definition, a one-way operation. You don't decrypt anything using MD5. When a user registers, you hash their password and store the result. When the user logs in, you hash the password they provide and compare that result to the value in the database. If they match then the user is authenticated, otherwise they are not. There is no simple way to get the original value back from an MD5 hash and that is the whole point. If you want to be able to decrypt the data then you need to use a symmetric encryption algorithm.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3

    Thread Starter
    Lively Member
    Join Date
    Aug 2016
    Posts
    69

    Re: CryptographicException : Access violation

    How come from the video the person is able to do Encryption and Decryption?

    Also do you have an example for symmetric encryption algorithm?

  4. #4
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: CryptographicException : Access violation

    I just looked at your code. You're using Triple DES for encryption/decryption. MD5 is just for hashing the encryption key.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  5. #5
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    4,578

    Re: CryptographicException : Access violation

    "First chance" exception handlers are the debugger trying to help. The program breaks for them the moment they're thrown, without checking to see if they will be handled. So generally, I ignore them in terms of bug hunting, because they only matter if they are unhandled.

    Try running your program outside of the debugger and see if this exception persists. If it does, it ought to get re-wrapped into a more informative exception. If it doesn't, then it wasn't actually a problem in the first place.

    (Also, I don't really understand the value of hashing the key to an encryption algorithm. Public keys are supposed to be public, private keys are supposed to be private, and if the latter is violated the hashing doesn't accomplish anything at all. Maybe I'm ignorant about cryptography, but that feels like a step that doesn't really do anything.)

    (And actually, it looks like your program does crash? Generally you ought to be able to tell what's going wrong from catching the outer exception. Isn't the debugger showing an assistant for that one? CryptographicException ought to have a message.)

    Also: why do you make your fellow experts cry and use VB6-oriented file I/O APIs?
    Last edited by Sitten Spynne; Oct 27th, 2016 at 08:38 AM.

  6. #6
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    4,578

    Re: CryptographicException : Access violation

    Also, you might want to have a look at The Bathroom Wall of Code.

    It turns out that ECB mode is a very insecure cipher mode, and the punch line to a bit of a joke in the encryption community. The joke: almost every example of encryption available on the internet has copy/pasted the same code from another erroneous example and passed it off as "the way". Read that article, and the one it links, very closely. It makes suggestions for implementing encryption in ways that aren't as vulnerable.

    Cryptography is a topic you can't apply with a magic brush, you have to understand a little bit of it to use it well.

  7. #7
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    4,578

    Re: CryptographicException : Access violation

    Oh, ah. One thing to check. Most encryption algorithms are very specific about the size of the data you feed them. You'd think you'd find that in the MSDN documentation, but they apparently are comfortable with the fact that no one reads it anyway and decided to omit that.

    Triple DES wants 64-byte block sizes. If the array 'Buffer' is not a multiple of 64, it would lead to this exception. Generally, when that happens, you have to create an array that's padded with null bytes at the end.

    The same goes for keys. Triple DES wants them to be exactly a certain size, maybe that's why MD5 is being used on the key.

    You might say, "But why would the base64 string not be exactly the right size if it represents encrypted data?" It probably is. But what if it has a newline appended, because you read it from the file? That'd add at least a byte to the string you pass to GetBytes(), which would result in your ciphertext being larger than it was when generated. So you need to check for extra whitespace and get rid of it.

    Either way, your code's structured to make it impossible for you to check these things. Try rewriting it so that the result of each function call is stored in a variable, so that you can debug through it line by line and verify everything. When you cram everything onto one line, you hurt yourself in many ways. It'sliketypinganessaywithoutspacestotryandsavetime.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width