Results 1 to 3 of 3

Thread: AES Encryption and bound textbox

  1. #1

    Thread Starter
    Fanatic Member
    Join Date
    Aug 2005
    Posts
    606

    AES Encryption and bound textbox

    I'm having quite a time trying to figure this out and hope someone here can help.

    I have several textboxes bound to an Access db as the backend. One of these textboxes is a masked (SSN) textbox, obviously for a SSN

    What I want to do is:
    When I click my save button on the BindingNavigator, I want to take the text of the SSN textbox, encrypt it and save it to my db.

    That in itself isn't the problem.

    I think my problem is that because the data is changing in the db when I save the encrypted string and because my SSN textbox is bound to the db, my SSN textbox.text also changes to some crazy text but not the encrypted string.

    So I have the decryption code in the Load event also so when the user fires up the form it shows the correct data in the SSN textbox. I think that all works, I just can't figure out how to stop teh SSN textbox from changing upon the save of the data.

    Does this make any sense to anyone?

    Here's my code to accomplish the above:

    Code:
    Public Class Form1
    
       
        Private UserRow As ErvDataDataSet.ResponsibleEntitysRow
    
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    
            'TODO: This line of code loads data into the 'ErvDataDataSet.ResponsibleEntitys' table. 
            Me.ResponsibleEntitysTableAdapter.Fill(Me.ErvDataDataSet.ResponsibleEntitys)
    
            'Create new instance of AESExample
            Dim AesExample As New Encrypt_Decrypt.AesExample
            'Create a Key String
            Dim KeyString As String = (FNameTextBox.Text.Trim() + _
                                          LNameTextBox.Text.Trim() + StreetNoTextBox.Text.Trim())
            Try
                'Get the first row in the table
                UserRow = CType(CType(Me.ResponsibleEntitysBindingSource.Current, DataRowView).Row, ErvDataDataSet.ResponsibleEntitysRow)
                'Decrypt what is held in the datatable SSN field and show it in the SSN textbox
                SSNTextBox.Text = AesExample.Decrypt(UserRow.SSN.Trim(), KeyString.Trim())
    
            Catch ex As Exception
                'If no rows are returned then show nothing in the SSN textbox
                SSNTextBox.Text = ""
            End Try
    
        End Sub
    
    
    
        Private Sub ResponsibleEntitysBindingNavigatorSaveItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ResponsibleEntitysBindingNavigatorSaveItem.Click
    
            'Create new instance of AESExample
            Dim AesExample As New Encrypt_Decrypt.AesExample
            'Create a Key String
            Dim KeyString As String = (FNameTextBox.Text.Trim() + _
                                          LNameTextBox.Text.Trim() + StreetNoTextBox.Text.Trim())
    
            'Assign the SSN field of the UserRow with the encrypted string
            UserRow.SSN = AesExample.Encrypt(SSNTextBox.Text.Trim(), KeyString.Trim())
    
            'Save to the db
            Me.Validate()
            Me.ResponsibleEntitysBindingSource.EndEdit()
            Me.TableAdapterManager.UpdateAll(Me.ErvDataDataSet)
    
        End Sub
    End Class
    And the encryption/decryption code.

    Code:
    Imports System.IO
    Imports System.Text
    Imports System.Security.Cryptography
    
    Public Class AesExample
    
        Public Function Encrypt(SSN As String, KeyString As String) As String
    
            'Add the following string to the Key string so that the cypher is even harder to decypher
            Dim EncryptionKey As String = (KeyString + "797474694B5F6F6C6C6548".Trim())
            Dim clearBytes As Byte() = Encoding.Unicode.GetBytes(SSN)
            Using encryptor As Aes = Aes.Create()
                Dim pdb As New Rfc2898DeriveBytes(EncryptionKey, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D, _
                 &H65, &H64, &H76, &H65, &H64, &H65, &H76})
                encryptor.Key = pdb.GetBytes(32)
                encryptor.IV = pdb.GetBytes(16)
                Using ms As New MemoryStream()
                    Using cs As New CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write)
                        cs.Write(clearBytes, 0, clearBytes.Length)
                        cs.Close()
                    End Using
                    SSN = Convert.ToBase64String(ms.ToArray())
                End Using
            End Using
            Return SSN
    
        End Function
    
        Public Function Decrypt(EncrytpedText As String, KeyString As String) As String
    
            'Add the following string to the cypher string so that the cypher string is even harder to decypher
            Dim EncryptionKey As String = (KeyString + "797474694B5F6F6C6C6548".Trim())
            Dim cipherBytes As Byte() = Convert.FromBase64String(EncrytpedText)
            Using encryptor As Aes = Aes.Create()
                Dim pdb As New Rfc2898DeriveBytes(EncryptionKey, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D, _
                 &H65, &H64, &H76, &H65, &H64, &H65, &H76})
                encryptor.Key = pdb.GetBytes(32)
                encryptor.IV = pdb.GetBytes(16)
                Using ms As New MemoryStream()
                    Using cs As New CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write)
                        cs.Write(cipherBytes, 0, cipherBytes.Length)
                        cs.Close()
                    End Using
                    EncrytpedText = Encoding.Unicode.GetString(ms.ToArray())
                End Using
            End Using
            Return EncrytpedText
        End Function
    
    End Class
    Life is about making some things happen, not waiting around for something to happen.

  2. #2
    Frenzied Member
    Join Date
    Oct 2012
    Location
    Tampa, FL
    Posts
    1,187

    Re: AES Encryption and bound textbox

    There are a few ways to do this, I was able to get this to work for me using your encryption functions. You load in the data, then you immediately make a call to decrypt the data in the datatable. At time of saving, you encrypt all the data in the datatable, save it back, then decrypt it again after the update has finished.

    Code:
    Imports System.Text
    Imports System.Security.Cryptography
    Imports System.IO
    
    Public Class Form1
        Dim keyString As String = "TEST"
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            'TODO: This line of code loads data into the 'TestDBDataSet.tblSSN' table. You can move, or remove it, as needed.
            Me.TblSSNTableAdapter.Fill(Me.TestDBDataSet.tblSSN)
            UpdateTableRowEncryption(False)
    
        End Sub
    
        Private Sub TblSSNBindingNavigatorSaveItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TblSSNBindingNavigatorSaveItem.Click
            Me.Validate()
            Me.TblSSNBindingSource.EndEdit()
    
            UpdateTableRowEncryption(True)
            Me.TableAdapterManager.UpdateAll(Me.TestDBDataSet)
            UpdateTableRowEncryption(False)
    
        End Sub
    
        Public Sub UpdateTableRowEncryption(ByVal encryptRows As Boolean)
    
            For Each row In TestDBDataSet.tblSSN
                If encryptRows Then
                    row.SSN = EncryptString(row.SSN, keyString)
                Else
                    row.SSN = DecryptString(row.SSN, keyString)
                End If
            Next row
    
    
        End Sub
    
    End Class
    
    Public Module AesExample
    
        Public Function EncryptString(ByVal SSN As String, ByVal KeyString As String) As String
    
            'Add the following string to the Key string so that the cypher is even harder to decypher
            Dim EncryptionKey As String = (KeyString + "797474694B5F6F6C6C6548".Trim())
            Dim clearBytes As Byte() = Encoding.Unicode.GetBytes(SSN)
            Using encryptor As Aes = Aes.Create()
                Dim pdb As New Rfc2898DeriveBytes(EncryptionKey, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D, _
                 &H65, &H64, &H76, &H65, &H64, &H65, &H76})
                encryptor.Key = pdb.GetBytes(32)
                encryptor.IV = pdb.GetBytes(16)
                Using ms As New MemoryStream()
                    Using cs As New CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write)
                        cs.Write(clearBytes, 0, clearBytes.Length)
                        cs.Close()
                    End Using
                    SSN = Convert.ToBase64String(ms.ToArray())
                End Using
            End Using
            Return SSN
    
        End Function
    
        Public Function DecryptString(ByVal EncrytpedText As String, ByVal KeyString As String) As String
    
            'Add the following string to the cypher string so that the cypher string is even harder to decypher
            Dim EncryptionKey As String = (KeyString + "797474694B5F6F6C6C6548".Trim())
            Dim cipherBytes As Byte() = Convert.FromBase64String(EncrytpedText)
            Using encryptor As Aes = Aes.Create()
                Dim pdb As New Rfc2898DeriveBytes(EncryptionKey, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D, _
                 &H65, &H64, &H76, &H65, &H64, &H65, &H76})
                encryptor.Key = pdb.GetBytes(32)
                encryptor.IV = pdb.GetBytes(16)
                Using ms As New MemoryStream()
                    Using cs As New CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write)
                        cs.Write(cipherBytes, 0, cipherBytes.Length)
                        cs.Close()
                    End Using
                    EncrytpedText = Encoding.Unicode.GetString(ms.ToArray())
                End Using
            End Using
            Return EncrytpedText
        End Function
    
    End Module

  3. #3

    Thread Starter
    Fanatic Member
    Join Date
    Aug 2005
    Posts
    606

    Re: AES Encryption and bound textbox

    Hmm, interesting, just running the decrypt again after the save. Now why didn't I think of that. I was thinking of just un-binding the SSN textbox all together.
    And although I like the fact that you throw in encryption on all rows of the table, I think I'll only be working with one row at a time. via a filter on the bindingsource.

    I'm just trying to gather some ideas how I could store and retrieve sensitive information in a real world app. and actually make them work.

    Thanks for the idea.
    Life is about making some things happen, not waiting around for something to happen.

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