System.Security.Cryptography.CryptographicException: 'Bad Data. ' triple DES encryption vb.net ms acces

352 Views Asked by At

Encryption and Decryption

Imports System.Security.Cryptography
Imports System.Text
Imports System.IO



Public Class EncDecCls

    Private tripleDES As New TripleDESCryptoServiceProvider

    'Public Sub New(_KEY As String)
    '    KeyStr = _KEY
    'End Sub

    'Private KeyValue As String
    'Public Property KeyStr() As String
    '    Get
    '        Return KeyValue
    '    End Get
    '    Set(value As String)
    '        KeyValue = value
    '    End Set
    'End Property

    Function Encryption(ByVal datafile As String) As String

        Dim input As Byte() = System.Text.Encoding.Unicode.GetBytes(datafile)

        Dim ms As New System.IO.MemoryStream
        Dim encstream As New CryptoStream(ms, tripleDES.CreateEncryptor(),
                      System.Security.Cryptography.CryptoStreamMode.Write)

        encstream.Write(input, 0, input.Length)

        encstream.FlushFinalBlock()

        Return Convert.ToBase64String(ms.ToArray)

    End Function

    Function Decryption(ByVal encryptedfile As String) As String

        Dim output() As Byte = System.Text.Encoding.Unicode.GetBytes(encryptedfile)

        Dim ms As New System.IO.MemoryStream
        Dim decstream As New CryptoStream(ms, tripleDES.CreateDecryptor(),
                     System.Security.Cryptography.CryptoStreamMode.Write)

        decstream.Write(output, 0, output.Length)

        decstream.FlushFinalBlock()

        Return System.Text.Encoding.Unicode.GetString(ms.ToArray)
    End Function
End Class

Code to retrieve data from database and decrypt it, then to display on datagridview(DGVSV)

Dim cmd1 As New OleDbCommand("SELECT * FROM pwdmgr WHERE username = @uname", conn)
        cmd1.Parameters.Add("@uname", OleDbType.VarChar).Value = x
        conn.Open()
        dr = cmd1.ExecuteReader
        dr.Read()
        DGVSV.Rows.Add(dr.Item("id").ToString,
                           EncryptDecryptFiles.Decryption(dr.Item("email").ToString),
                                EncryptDecryptFiles.Decryption(dr.Item("pwd").ToString))
        
        conn.Close()

There are few rows of data to be retrieved and to display it into the datagridview(DGVSV). Everytime when i run this function above it shows this error System.Security.Cryptography.CryptographicException: 'Bad Data. '

Can someone help me on that?

0

There are 0 best solutions below