Click here to Skip to main content
15,903,030 members
Home / Discussions / Visual Basic
   

Visual Basic

 
GeneralRe: Delete/Remove test certificate Pin
vijay248217-Nov-10 4:24
vijay248217-Nov-10 4:24 
GeneralRe: Delete/Remove test certificate Pin
Dave Kreskowiak17-Nov-10 5:09
mveDave Kreskowiak17-Nov-10 5:09 
GeneralRe: Delete/Remove test certificate Pin
vijay248217-Nov-10 5:27
vijay248217-Nov-10 5:27 
GeneralRe: Delete/Remove test certificate Pin
Dave Kreskowiak17-Nov-10 5:45
mveDave Kreskowiak17-Nov-10 5:45 
GeneralRe: Delete/Remove test certificate Pin
vijay248217-Nov-10 21:35
vijay248217-Nov-10 21:35 
QuestionNeed some help trying to figure this out. Pin
crain198116-Nov-10 13:23
crain198116-Nov-10 13:23 
AnswerRe: Need some help trying to figure this out. Pin
Dave Kreskowiak16-Nov-10 14:55
mveDave Kreskowiak16-Nov-10 14:55 
GeneralRe: Need some help trying to figure this out. Pin
crain198116-Nov-10 16:26
crain198116-Nov-10 16:26 
Well... its a custom made format(.fva). All files are encrypted and made into one file. Than when you want to extract from the file, the application will decrypt and extract the file for you. However, the location/position of the data within the file is in an xml but I'm not having any trouble with this part.

However one problem that's been annoying me for about a week is when you encryption small files, its hard to decrypt it(I'll post the code soon).

The second problem is when you delete from the datagridview. Here is the use case:
1. User selects file from datagridview.
2. User presses delete to delete the file.
3. Application deletes the file in the secure archive location.(this is the problem)
4. Application deletes the file from the xml.(not a problem)
5. Application keeps running until user exits out.



Here is the full code below. Please note I've deleted from the problem section because I've been trying things and googling alot lately.
Imports System.Xml
Imports System.Object
Imports System.Security
Imports System.Security.Cryptography

Imports System.IO
Imports System.IO.Compression
Imports Ionic.Zip


Public Class EncryptDecryptForm
    Public index As Integer
    Private Sub EncryptDecryptFormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

        File_DataGridView.Rows.Clear()
        Environment.Exit(0)
    End Sub



    Private Sub Encrypt_Browse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Encrypt_Browse.Click
        'The code below will open a dialog bos '
        Dim find As OpenFileDialog = New OpenFileDialog()
        find.Title = "File Vault application" 'Title of file browser'
        find.InitialDirectory = "c:\"
        find.AddExtension = True
        find.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
        find.FilterIndex = 2
        find.RestoreDirectory = True
        If find.ShowDialog() = Windows.Forms.DialogResult.OK Then
            Me.Encrypt_TextBox.Text = find.FileName


        End If
    End Sub

    Private Sub Decrypt_Browse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Decrypt_Browse.Click
        'Code below will start the folder browser'
        Dim folder As FolderBrowserDialog = New FolderBrowserDialog()
        folder.Description = "Select Folder"
        folder.RootFolder = Environment.SpecialFolder.MyComputer
        If folder.ShowDialog = Windows.Forms.DialogResult.OK Then
            Me.Decrypt_TextBox.Text = folder.SelectedPath.ToString
        End If

    End Sub



    Private Sub Encrypt_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Encrypt.Click
        encryption()
    End Sub
    Private Sub reload()
        'This functions reloads the datagrid with the new updated information'
        'Replaces the format so the application can read it'
        
        Dim xdoc As XmlDocument = New XmlDocument
        xdoc.Load("Resources\FileVault.xml")
        Dim name As XmlNodeList = xdoc.GetElementsByTagName("*******")
        Dim count As Integer
        For count = 0 To (name.Count - 1)
            File_DataGridView.Rows.Add(name.Item(count).InnerText.ToString, name.Item(count).InnerText.ToString)
        Next count
        File_DataGridView.AutoResizeColumns()
        File_DataGridView.AutoResizeRows()

    End Sub


    Private Sub Decrypt_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Decrypt.Click
        decryption()

    End Sub
    


    Private Sub EncryptDecryptForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'When the forms load, this sets up the initial columns and what the user can and can not do to them.'
        File_DataGridView.Columns.Add("File name", "File name")
        File_DataGridView.ColumnHeadersVisible = True
        File_DataGridView.ColumnCount = 1
        File_DataGridView.AllowUserToResizeColumns = False
        File_DataGridView.AllowUserToAddRows = False
        File_DataGridView.AllowUserToResizeRows = False
        File_DataGridView.AllowUserToOrderColumns = False
        File_DataGridView.AllowDrop = False
        File_DataGridView.AllowUserToDeleteRows = True
        File_DataGridView.AutoGenerateColumns = True



        Dim xdoc As XmlDocument = New XmlDocument

        xdoc.Load("Resources\FileVault.xml") 'Load Xml file -> declare location here'
        Dim name As XmlNodeList = xdoc.GetElementsByTagName("*******") 'Counts these elements'

        Dim count As Integer
        For count = 0 To (name.Count - 1) 'This for loop fills the data'
            File_DataGridView.Rows.Add(name.Item(count).InnerText.ToString, name.Item(count).InnerText.ToString)
        Next count


        

    End Sub

    'This function creates the encryption key' 
    Private Function keyencryption(ByVal strPassword As String) As Byte()
        'Converting the character to an array and storing the data
        Dim chrdata() As Char = strPassword.ToCharArray

        'Make is the same length'
        Dim Length As Integer = chrdata.GetUpperBound(0)

        'starting to hash the data'
        Dim bytDataToHash(Length) As Byte

        For i As Integer = 0 To chrdata.GetUpperBound(0)
            bytDataToHash(i) = CByte(Asc(chrdata(i)))
        Next

        'Declaring what Hash to use'
        Dim SHA512 As New System.Security.Cryptography.SHA512Managed

        'Hashing'
        Dim Result As Byte() = SHA512.ComputeHash(bytDataToHash)

        Dim resIV(31) As Byte

        For i As Integer = 0 To 31
            resIV(i) = Result(i)
        Next
        Return resIV
    End Function

    'Identical function from above except for a few lines
    Private Function IVCreation(ByVal strPassword As String) As Byte()
        'Converting the character to an array and storing the data
        Dim chrdata() As Char = strPassword.ToCharArray

        'Make is the same length'
        Dim Length As Integer = chrdata.GetUpperBound(0)

        'starting to hash the data'
        Dim bytDataToHash(Length) As Byte

        For i As Integer = 0 To chrdata.GetUpperBound(0)
            bytDataToHash(i) = CByte(Asc(chrdata(i)))
        Next

        'Declaring what Hash to use'
        Dim SHA512 As New System.Security.Cryptography.SHA512Managed

        'Hashing'
        Dim Result As Byte() = SHA512.ComputeHash(bytDataToHash)

        Dim resIV(15) As Byte

        For i As Integer = 32 To 47
            resIV(i - 32) = Result(i)
        Next
        Return resIV
    End Function

    Private Function encryption()

        'This sub will encrypt the file, xml edits, update the gridview'
        'loading the xml document'
        Dim xdoc As XmlDocument = New XmlDocument
        Dim key As Byte()
        Dim IV As Byte()

        'The hardcoded password goes here'
        'This is a section just in case you want to a password to your encrypted files'
        'Right now it uses the hardcoded password'
        'If you can expand this if you want'
        key = keyencryption(LoginForm.Password_TextBox.Text)
        IV = IVCreation(LoginForm.Password_TextBox.Text)
        'if there is an error in the application. A error message will be displayed'
        Try
            'checking to make sure the text box isn't null'
            If (Encrypt_TextBox.Text = "") Then
                MessageBox.Show("Need to put in a file location")
            Else

                


                'Grabing the file name'
                Dim locatefilename As String = Me.Encrypt_TextBox.Text
                Dim i As Integer = 0
                Dim fnPosition As Integer = 0
                'locating all the \ in the string'
                While locatefilename.IndexOf("\"c, i) <> -1
                    fnPosition = locatefilename.IndexOf("\"c, i)
                    i = fnPosition + 1
                End While

                Dim junk As String
                Dim tfile As String
                Dim file As String
                Dim ext As String
                'This should get all the junk that not need for saving files'
                'This should capture what you don't need'
                junk = locatefilename.Substring(0, fnPosition)
                'This should capture the file' 
                tfile = locatefilename.Substring(fnPosition + 1)
                'Zeroing both i and fnPosition'
                i = 0
                fnPosition = 0
                'taking out the extention in the file and saving it to the xml'
                While tfile.IndexOf("."c, i) <> -1
                    fnPosition = tfile.IndexOf("."c, i)
                    i = fnPosition + 1
                End While
                'This should get the actually file name'
                file = tfile.Substring(0, fnPosition)

                'captures the ext (like the txt)'
                'Makes the format of the file invisible but only in the xml'
                ext = "." & tfile.Substring(fnPosition + 1)

                'Checking to make sure there are not duplicate file name'
                Dim name As XmlNodeList = xdoc.GetElementsByTagName("*******")
                Dim cname As Integer
                For cname = 0 To (name.Count - 1)
                    If (file = name.Item(cname).InnerText) Then
                        MessageBox.Show("Duplicate file name - either delete the file present in safe or rename file")
                        Return 1
                    End If
                Next
                'This is the file being read in'
                Dim fileinput As New System.IO.FileStream(Me.Encrypt_TextBox.Text, IO.FileMode.Open, IO.FileAccess.Read)
                'specific file output location here
                Dim fileoutput As New System.IO.FileStream("*******", IO.FileMode.Open, IO.FileAccess.Write)

                Dim start As Integer = fileoutput.Length

                'Declaring variables for encryption'

                Dim buffer(4096) As Byte 'Holds the bytes for processing

                Dim BytesProcessed As Long = 0 'running count for bytes that are processed'

                Dim filelength As Long = fileinput.Length 'Length of file coming in'

                Dim bytesinblock As Integer 'current bytes in block'

                Dim crypto As CryptoStream

                'Declaring crypto service provider'
                Dim scRijndael As New System.Security.Cryptography.RijndaelManaged

                'setting up progress bars
                Encrypt_ProgressBar.Value = 0
                Encrypt_ProgressBar.Maximum = 100

                crypto = New CryptoStream(fileoutput, scRijndael.CreateEncryptor(key, IV), CryptoStreamMode.Write)

                While BytesProcessed < filelength
                    'reading the file'
                    bytesinblock = fileinput.Read(buffer, 0, 4096)
                    'writing the file to cryptoStream'
                    crypto.Write(buffer, 0, bytesinblock)
                    'updating bytes processed'
                    BytesProcessed = BytesProcessed + CLng(bytesinblock)
                    'equation for updating bytes in block'
                    Encrypt_ProgressBar.Value = CInt((BytesProcessed / filelength) * 100)
                End While
                Dim filend As Integer = fileoutput.Length
                crypto.Close()
                fileinput.Close()

                fileoutput.Close()
                MessageBox.Show("File is done encrypting")
                Encrypt_ProgressBar.Step = 0
                Encrypt_ProgressBar.Value = 0
                Encrypt_TextBox.Text = ""
                'End While


           

                'loading the xml file
                xdoc.Load("*******")
                'variable for adding a new line' 
                Dim nline As String = Environment.NewLine
                'Creating string for xml file with proper formats'
                Dim xmlString As String = nline & "   <file>" & nline & "       <name>" & file & "</name>" & nline & "       <location>" & "Safe\" & file & "</location>" & nline & "       <ext>" & ext & "</ext>" & nline & " <beginbyte>" & start & "</beginbyte>" & nline & "    <endbytes>" & filend & "</endbytes>" & nline & "    </file>" & nline
                'the following is used to add the element to the xml'
                Dim frag As XmlDocumentFragment = xdoc.CreateDocumentFragment
                'Adds the xmlstring to the frag'
                frag.InnerXml = xmlString
                Dim xroot As XmlNode = xdoc.DocumentElement
                'the following statements will add on to the file and save the file'
                xroot.AppendChild(frag)
                xdoc.Save("*******")
                'Clearing the datagrid and reloading the new data, to the eye it you will just blink'
                File_DataGridView.Hide()
                File_DataGridView.Rows.Clear()

                'function reloads the updated xml file'
                reload()

                File_DataGridView.Show()


            End If
        Catch ex As Exception
            MsgBox(ex.Message)

        End Try
        Return 1
    End Function
    Private Function decryption()

        'This is function is the same as encryption with just a few changes'
        'loading the xml document'
        Dim xdoc As XmlDocument = New XmlDocument
        Dim key As Byte()
        Dim IV As Byte()

        'The hardcoded password goes here'
        'This is a section just in case you want to a password to your encrypted files'
        key = keyencryption(LoginForm.Password_TextBox.Text)
        IV = IVCreation(LoginForm.Password_TextBox.Text)
        'if there is an error in the application. A error message will be displayed'
        Try

            'checking to make sure the text box isn't null'
            If (Decrypt_TextBox.Text = "") Then
                MessageBox.Show("Need to put in the file location or select file in grid for decryption")
            Else

                'declaring string for file'
                Dim file As String
                Dim tfile As String
                Dim deleteExt As String
                Dim output As String
                Dim fnPosition As Integer
                Dim i As Integer

                'locating the selected file in the gridview'
                'loading the xml file
                xdoc.Load("*******")
                'Declare name for xml node'
                Dim name As XmlNodeList = xdoc.GetElementsByTagName("*******")
                'file location is now saved
                file = name.Item(index).InnerText
                'Substring of file. This is will be convering the file back to its normal
                tfile = file.Substring(5)
                'retrieving the extenstion'
                Dim extname As XmlNodeList = xdoc.GetElementsByTagName("*******")
                Dim replace As String
                deleteExt = extname.Item(index).InnerText
                'replacing with proper format'
                While tfile.IndexOf("."c, i) <> -1
                    fnPosition = tfile.IndexOf("."c, i)
                    i = fnPosition + 1
                End While
                'This should get the actually file name'
                replace = (tfile & deleteExt)
                'setting the output file with proper format'
                output = Decrypt_TextBox.Text & "\" & replace
                Dim filebegin As XmlNodeList = xdoc.GetElementsByTagName("*******")
                Dim filend As XmlNodeList = xdoc.GetElementsByTagName("*******")
                Dim intStart As Integer = filebegin.Item(index).InnerText
                Dim intEnd As Integer = filend.Item(index).InnerText
                'This is go into the Safe and retrieve file'
                Dim fileinput As New System.IO.FileStream("Safe.fva", IO.FileMode.Open, IO.FileAccess.Read)
                'specific file output location wiht proper extension'
                Dim fileoutput As New System.IO.FileStream(output, IO.FileMode.OpenOrCreate, IO.FileAccess.Write)
                'The next line makes sure that the file is empty'
                fileoutput.SetLength(0)

                'Declaring variables for encryption'

                Dim buffer(4096) As Byte 'Holds the bytes for processing

                Dim BytesProcessed As Long = 0 'running count for bytes that are processed'

                Dim filelength As Long = intEnd - intStart 'Length of file coming in where intEnd will be greater than intStart'

                Dim bytesinblock As Integer 'current bytes in block

                Dim crypto As CryptoStream

                'Declaring crypto service provider'
                Dim scRijndael As New System.Security.Cryptography.RijndaelManaged

                'setting up progress bars
                Encrypt_ProgressBar.Value = 0
                Encrypt_ProgressBar.Maximum = 100

                crypto = New CryptoStream(fileoutput, scRijndael.CreateDecryptor(key, IV), CryptoStreamMode.Write)
                fileinput.Position = intStart
                While BytesProcessed < filelength
                    'reading the file'h
                    bytesinblock = fileinput.Read(buffer, 0, 4096)
                    'writing the file to cryptoStream'
                    crypto.Write(buffer, 0, bytesinblock)
                    'updating bytes processed'
                    BytesProcessed = BytesProcessed + CLng(bytesinblock)
                    'equation for updating bytes in block'
                    Decrypt_ProgressBar.Value = CInt((BytesProcessed / filelength) * 100)
                End While
                If (filelength = 0) Then
                    bytesinblock = fileinput.Read(buffer, 0, 4096)
                    crypto.Write(buffer, 0, bytesinblock)
                End If
                crypto.Close()
                fileinput.Close()
                fileoutput.Close()
                MessageBox.Show("File is done decrypting")
                Decrypt_ProgressBar.Step = 0
                Decrypt_ProgressBar.Value = 0
                Decrypt_TextBox.Text = ""
            End If
        Catch ex As Exception
            MsgBox(ex.StackTrace.ToString)
        End Try

        Return 1
    End Function

    Public Sub File_DataGridView_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles File_DataGridView.CellClick
        index = e.RowIndex

    End Sub



    Private Sub File_DataGridView_UserDeletingRow(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowCancelEventArgs) Handles File_DataGridView.UserDeletingRow
        Dim xdoc As XmlDocument = New XmlDocument
        xdoc.Load("*******")

        Dim filebegin As XmlNodeList = xdoc.GetElementsByTagName("*******")
        Dim filend As XmlNodeList = xdoc.GetElementsByTagName("*******")
        Dim intStart As Integer = filebegin.Item(index).InnerText
        Dim intEnd As Integer = filend.Item(index).InnerText

        Dim deletefile As New System.IO.FileStream("*******", FileMode.Open)
        Dim deletethis As Integer = CLng(deletefile.Length)

        







        'Deletes the actual file'
        Dim location As XmlNodeList = xdoc.GetElementsByTagName("*******")
        Dim del_location As String = location.Item(index).InnerText

        'Deletes the information in the xml'
        Dim name As XmlNodeList = xdoc.GetElementsByTagName("*******")
        name.Item(index).RemoveAll()
        name.Item(index).ParentNode.RemoveChild(name.Item(index))
        xdoc.Save("********")


    End Sub



End Class


All help will be greatly appriecated.
GeneralRe: Need some help trying to figure this out. Pin
Dave Kreskowiak16-Nov-10 17:15
mveDave Kreskowiak16-Nov-10 17:15 
GeneralRe: Need some help trying to figure this out. Pin
crain198118-Nov-10 13:01
crain198118-Nov-10 13:01 
GeneralRe: Need some help trying to figure this out. Pin
Dave Kreskowiak18-Nov-10 13:26
mveDave Kreskowiak18-Nov-10 13:26 
GeneralRe: Need some help trying to figure this out. Pin
crain198118-Nov-10 14:35
crain198118-Nov-10 14:35 
GeneralRe: Need some help trying to figure this out. Pin
Dave Kreskowiak18-Nov-10 16:58
mveDave Kreskowiak18-Nov-10 16:58 
GeneralRe: Need some help trying to figure this out. Pin
crain198119-Nov-10 1:55
crain198119-Nov-10 1:55 
GeneralRe: Need some help trying to figure this out. Pin
Dave Kreskowiak19-Nov-10 10:29
mveDave Kreskowiak19-Nov-10 10:29 
GeneralRe: Need some help trying to figure this out. Pin
crain198119-Nov-10 11:44
crain198119-Nov-10 11:44 
GeneralRe: Need some help trying to figure this out. Pin
Dave Kreskowiak20-Nov-10 13:59
mveDave Kreskowiak20-Nov-10 13:59 
GeneralRe: Need some help trying to figure this out. Pin
crain198120-Nov-10 14:52
crain198120-Nov-10 14:52 
GeneralRe: Need some help trying to figure this out. Pin
crain198119-Nov-10 11:11
crain198119-Nov-10 11:11 
GeneralRe: Need some help trying to figure this out. Pin
Dave Kreskowiak18-Nov-10 13:30
mveDave Kreskowiak18-Nov-10 13:30 
AnswerRe: Need some help trying to figure this out. Pin
Luc Pattyn16-Nov-10 17:24
sitebuilderLuc Pattyn16-Nov-10 17:24 
GeneralRe: Need some help trying to figure this out. Pin
crain198118-Nov-10 12:24
crain198118-Nov-10 12:24 
GeneralRe: Need some help trying to figure this out. Pin
Dave Kreskowiak18-Nov-10 13:28
mveDave Kreskowiak18-Nov-10 13:28 
GeneralRe: Need some help trying to figure this out. Pin
crain198118-Nov-10 14:34
crain198118-Nov-10 14:34 
GeneralRe: Need some help trying to figure this out. Pin
crain198119-Nov-10 15:05
crain198119-Nov-10 15:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.