encrypting a folder in vb.net - vb.net

I am currently trying to encrypt a Folder in VB.net. To do this, I am using In IO.Directory.GetFiles to get each file from the folder, and encrypt each file using a loop. Each encrypted file will then be saved to a location, in its original name . I am currently struggling to understand how to have the output file save each file in their original name. My code so far is displayed below, any help or guidance would be greatly appreciated.
Imports System.Windows.Forms
Imports System.Security.Cryptography
Imports System.Security
Imports System.Text
Imports System.IO
Imports System.Runtime.InteropServices
Public Class Folder
Private Sub Select_btn_Click(sender As Object, e As EventArgs) Handles Select_btn.Click
'Allows user to select folder
If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
FileSelect_tb.Text = FolderBrowserDialog1.SelectedPath
End If
' Gets files in folder
Dim directory As New IO.DirectoryInfo(FileSelect_tb.Text)
Dim directorylist As IO.FileInfo() = directory.GetFiles()
Dim dra As IO.FileInfo
'Lists files in listbox
For Each dra In directorylist
ListBox1.Items.Add(dra)
Next
End Sub
Private Sub Encrypt_btn_Click(sender As Object, e As EventArgs) Handles Encrypt_btn.Click
'Password authentication
Dim skey As String = InputBox("Enter a password of 8 characters:")
'Check its 8 characters and repeat until its correct
While skey.Length <> 8
skey = InputBox("Password is not correct. Please try again:")
End While
For Each filePath In IO.Directory.GetFiles(FolderBrowserDialog1.SelectedPath)
'Allows user to select file destination
If FolderBrowserDialog2.ShowDialog() = DialogResult.OK Then
Encrypted_tb.Text =
End If
'Reads the file to create encryption
Dim fsInput As New FileStream(filePath, FileMode.Open, FileAccess.Read)
Dim fsEncrypted As New FileStream(Encrypted_tb.Text, FileMode.Create, FileAccess.Write)
'Defines encryption method
Dim DES As New DESCryptoServiceProvider
DES.Key = ASCIIEncoding.ASCII.GetBytes(skey)
DES.IV = ASCIIEncoding.ASCII.GetBytes(skey)
'Encrypts File
Dim desencrypt As ICryptoTransform
desencrypt = DES.CreateEncryptor()
Dim cryptostream As New CryptoStream(fsEncrypted, desencrypt, CryptoStreamMode.Write)
Dim bytearrayinput(fsInput.Length) As Byte
fsInput.Read(bytearrayinput, 0, bytearrayinput.Length)
cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length)
cryptostream.Close()
fsInput.Close()
fsEncrypted.Close()
Next
End Sub

Related

Whats wrong with my filesystem watcher code VB.NET?

when my file system watcher detects a virus a dialog shows but when i click the delete file option it says its open in my program but in the filesystem watcher when i add the openfiledialog.Dispose function it doesnt show my dialog so heres the code can somone provide a fix? code below.
Private Sub FileSystemWatcher1_Changed(ByVal sender As System.Object, ByVal e As System.IO.FileSystemEventArgs) Handles FileSystemWatcher1.Changed
Try
Detect.Labellastreal.Text = e.FullPath
ListBox3.Items.Add(Detect.Labellastreal.Text)
Me.OpenFileDialog3.FileName = ""
Dim scanbox As New TextBox
scanbox.Text = My.Computer.FileSystem.ReadAllText(Application.StartupPath & "\VirusList.dat").ToString
Dim md5 As New MD5CryptoServiceProvider
Dim f As New FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.Read, &H2000)
f = New FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.Read, &H2000)
md5.ComputeHash(f)
Dim hash As Byte() = md5.Hash
Dim buff As New StringBuilder
Dim hashByte As Byte
For Each hashByte In hash
buff.Append(String.Format("{0:X2}", hashByte))
Next
f.Close()
If scanbox.Text.Contains(buff.ToString) Then
Me.OpenFileDialog3.FileName = e.FullPath
Detect.ShowDialog()
WriteToLog("Virus detected")
End If
Catch exception1 As Exception
ProjectData.SetProjectError(exception1)
Dim ex As Exception = exception1
ProjectData.ClearProjectError()
End Try
End Sub
Firstly, don't even bother using that code. FileSystemWatcher is unreliable, and fails lots of the time.
Secondly, remove f = New FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.Read, &H2000), as you're calling it twice.
Lastly, for a Visual Basic anti-virus with real-time protection, I recommend you use this code:
Private Function GetMD5String(ByVal strFilename As String) As String
Dim MD5 As String = GetMD5String(strFilename)
Dim cMD5 = Security.Cryptography.MD5.Create
Dim bytHash As Byte()
Dim sb As New System.Text.StringBuilder
Dim scanbox As New TextBox
scanbox.Text = My.Computer.FileSystem.ReadAllText("viruslist.txt").ToString
Me.OpenFileDialog1.FileName = strFilename
Using cStream As New IO.FileStream(strFilename, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read)
bytHash = cMD5.ComputeHash(cStream)
End Using
For Each c In bytHash
sb.Append(c.ToString("X2"))
Next
If scanbox.Text.Contains(sb.ToString) Then
Detect.ShowDialog()
WriteToLog("Malicious exploit detected.")
Quarantinevb.ListBox1.Items.Add(strFilename)
End If
Return sb.ToString
End Function
Works well and is reliable.

How to Encrypt and Decrypt multiple text and image files within folders

Encryption and decryption for a single .txt file using the following code works:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles SelectFile.Click
'Create a File Dialog Box to select the source file
Dim dlg As New OpenFileDialog
'If OK Button is Click then add file name with path to textBox1
If dlg.ShowDialog() = DialogResult.OK Then
TextBox1.Text = dlg.FileName
End If
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Encrypt.Click
Dim outputFile As String
outputFile = "M:\Encryptions\Encrypted.txt"
Dim fsInput As New FileStream(TextBox1.Text, FileMode.Open, FileAccess.Read)
Dim fsEncrypted As New FileStream(outputFile, FileMode.Create, FileAccess.Write)
Dim sKey As String
sKey = "Helloabc"
Dim DES As New DESCryptoServiceProvider
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey)
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey)
Dim desencrypt As ICryptoTransform
desencrypt = DES.CreateEncryptor()
Dim cryptostream As New CryptoStream(fsEncrypted, desencrypt, CryptoStreamMode.Write)
Dim bytearrayinput(fsInput.Length) As Byte
fsInput.Read(bytearrayinput, 0, bytearrayinput.Length)
cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length)
cryptostream.Close()
fsInput.Close()
fsEncrypted.Close()
TextBox2.Text = "M:\Encryptions\Encrypted.txt"
End Sub
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Decrypt.Click
Dim DES As New DESCryptoServiceProvider
Dim sKey As String
sKey = "Helloabc"
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey)
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey)
Dim fsread As New FileStream(TextBox2.Text, FileMode.Open, FileAccess.Read)
Dim desdecrypt As ICryptoTransform
desdecrypt = DES.CreateDecryptor()
Dim cryptostreamDecr As New CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read)
Dim fsDecrypted As New StreamWriter("M:\Decryptions\Decrypted.txt")
fsDecrypted.Write(New StreamReader(cryptostreamDecr).ReadToEnd())
fsDecrypted.Flush()
fsDecrypted.Close()
TextBox3.Text = "M:\Decryptions\Decrypted.txt"
End Sub
However when attempting to encrypt/decrypt multiple files, the original output encryption/decryption file ("Encrypted.txt") will be replaced by the new output.
How do you create a loop in order to create multiple encrypted files with different file names?
Use a counter: 0, 1, 2, 3, 4 ... Append the counter to the filename and step the counter after each file is written:
Encrypted00.dat
Encrypted01.dat
Encrypted02.dat
Encrypted03.dat
...
It is probably a mistake to call the encrypted files .txt since they will not be text. They are binary data. If you want them as text then you will need to convert to Base64 format, and convert back to binary data before decrypting.
Alternatively, zip all the files in the directory into a single file and encrypt that single file.

File locked after encryption

I have a small app that is designed to go through a folder and encrypt all the files and delete the non-encrypted version. The encryption works correctly but when I go to delete the file it is locked. Once the app is closed the file is no longer locked. My code is
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim path As String = Directory.GetCurrentDirectory()
Dim parent As DirectoryInfo = Directory.GetParent(path)
Dim completions As String = parent.FullName & "\Attachments_Completions"
Dim di As New DirectoryInfo(completions)
Dim fi As FileInfo() = di.GetFiles()
Dim dra As FileInfo
For Each dra In fi
If dra.Name <> "Completions.txt" And dra.Name <> "Attachments.txt" Then
Dim tmpFileName As String = String.Format("{0}\qqzr_{1}", dra.DirectoryName, dra.Name)
Dim encryptedName As String = String.Format("{0}\{1}", dra.DirectoryName, dra.Name)
FileSystem.Rename(String.Format("{0}\{1}", dra.DirectoryName, dra.Name), String.Format("{0}\qqzr_{1}", dra.DirectoryName, dra.Name))
cryptFile(tmpFileName, encryptedName, False)
File.Delete(tmpFileName)
End if
Next
End Sub
Sub cryptFile(ByVal sInputFilename As String, ByVal sOutputFilename As String, ByVal switch As Boolean)
' * Used to Encrypt or Decrypt a file
' ***********************************
Dim sKey As String = "a2#R|+~"
Try
Dim DES As New DESCryptoServiceProvider()
DES.Key() = ASCIIEncoding.ASCII.GetBytes(sKey)
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey)
'Read the input file into array
Dim fsInput As New FileStream(sInputFilename, FileMode.Open, FileAccess.Read)
Dim bytearrayinput(fsInput.Length - 1) As Byte
fsInput.Read(bytearrayinput, 0, bytearrayinput.Length)
'Define the crypto transformer
Dim cryptoTransform As ICryptoTransform
If switch Then
cryptoTransform = DES.CreateEncryptor()
Else
cryptoTransform = DES.CreateDecryptor
End If
'Create the encrypting streams
Dim fsEncrypted As New FileStream(sOutputFilename, FileMode.Create, FileAccess.Write)
Dim cryptostream As New CryptoStream(fsEncrypted, cryptoTransform, CryptoStreamMode.Write)
'Write the output file
cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length)
cryptostream.Close()
cryptostream.Dispose()
'Release the input file
fsInput.Close()
fsInput.Dispose()
'Release the output file
fsEncrypted.Close()
fsEncrypted.Dispose()
Catch ex As Exception
End Try
End Sub
End Class
Can anyone help?
Cheers
James
Just add this
Catch ex As Exception
Debug.Write(ex.Message)
End Try
...and see what happens...
Thanks for the responses.
I have managed to resolve the problem by adding File.SetAttributes(tmpFileName, FileAttributes.Normal) before the File.Delete command

Im cant get a doc from my documents to display

Imports System.IO
Public Class Form1
Private Sub MenuItem1_Click(sender As Object, e As EventArgs) Handles MenuItem1.Click
Me.txtFileContent.Text = Nothing
End Sub
Private Sub MenuItem2_Click(sender As Object, e As EventArgs) Handles MenuItem2.Click
Me.txtFileContent.Text = Nothing
End Sub
Private Sub MenuItem3_Click(sender As Object, e As EventArgs) Handles MenuItem3.Click
Me.savSaveFile.ShowDialog()
Dim strFileName As String = Me.savSaveFile.FileName
Dim fs As New FileStream(strFileName, FileMode.Create, FileAccess.Write)
Dim TextFile As New StreamWriter(fs)
TextFile.Write(Me.txtFileContent.Text)
TextFile.Close()
fs.Close()
End Sub
Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles MenuItem5.Click
Me.savSaveFile.ShowDialog()
Dim strFileName As String = Me.savSaveFile.FileName
Dim fs As New FileStream(strFileName, FileMode.Open, FileAccess.Read)
Dim TextFile As New StreamWriter(fs)
TextFile.Close()
fs.Close()
End Sub
End Class
What im trying to do is display a "open" document dialog box so the text inside the box can be displayed into the text box. I did the same with the "save" document dialog box and it worked fine just confused on the Open part. Thanks a million everyone.
There are two different kind of dialog box for selecting files.
One for save operations and one for opening files.
Your code seems to use the same one and from the name I think it is a SaveFileDialog.
To open a file you need a OpenFileDialog and use a StreamReader not a StreamWriter
Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles MenuItem5.Click
' Create an OpenFileDialog here, for more precise property settings see the link above'
Dim openDlg = New OpenFileDialog()
' If user presses OK'
if openDlg.ShowDialog() = DialogResult.OK Then
' Still the filename selected could be empty, need to check'
Dim strFileName As String = openDlg.FileName
if strFileName.Trim().Length > 0 then
' Open the file using a reader, not a writer'
Using fs = New FileStream(strFileName, FileMode.Open, FileAccess.Read)
Using TextFile = New StreamReader(fs)
' Read everything (caution this should be used only for small files)'
Dim fileContent = TextFile.ReadToEnd
' Pass everything into a TextBox control for display'
Me.txtFileContent.Text = fileContent
End Using
End Using
End If
End If
End Sub

Trying to open a docx file from a bytestream - file corruption error

we consistently get a file corrupted error message when opening a docx file from a saved bytestream, evry other file type works just ok
Below is code from a sample form that replciate the issue
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Objective is to be able to copy a file to a bytestream then create a new document from that stream and then opne it.
'This replicates the behaviour of our primary application where it stores and retrieves the stream from a database
'With docx files we consistently experience some sort of corruption in the write of the original file
'When selecting .doc or other format files we do not encounter the same problem
'use selected file
Dim _o1 As String = TextBox1.Text
'get its bytestream
Dim fs As New FileStream(_o1, FileMode.Open, FileAccess.Read)
Dim byteStream(Convert.ToInt32(fs.Length)) As Byte
fs.Read(byteStream, 0, Convert.ToInt32(fs.Length))
'create a new file and use the bytestream to create it and save to disk
Dim _o As String = "C:\" & Now.Ticks & getNewFileName()
Dim fs1 As New FileStream(_o, FileMode.OpenOrCreate, FileAccess.Write)
Using bw As New BinaryWriter(fs1)
bw.Write(byteStream)
bw.Flush()
End Using
'open the new document
System.Diagnostics.Process.Start(_o)
Application.DoEvents()
End Sub
Private Function getNewFileName() As String
Dim fi As New FileInfo(TextBox1.Text)
Return Now.Ticks.ToString & fi.Name
End Function
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
OpenFileDialog1.InitialDirectory = "c:\"
OpenFileDialog1.FilterIndex = 2
OpenFileDialog1.RestoreDirectory = True
OpenFileDialog1.Filter = "docx files |*.docx"
If OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
TextBox1.Text = OpenFileDialog1.FileName
End If
End Sub
Forgive me, but that is some messed up code.
Dim _o As String = "C:\" & Now.Ticks & getNewFileName()
will become...
Dim _o As String = "C:\" & Now.Ticks & Now.Ticks.ToString & fi.Name
Example result "C:\" "634015010433498951" "634015010433498951" "FileName.txt" is probably not what you are expecting unless you intend to subtract the two tick counts to determine how long it took to populate FileInfo.
Your FileStream corruption could be a encoding issue, off by one file length issue, or even a long filename in a deep path could a problem. Instead of using FileStream, this code should work fine:
Dim sourceFile As String = TextBox1.text
Dim fi As New System.IO.FileInfo(sourceFile)
Dim destFile = "C:\" & Now.Ticks & fi.Name
fi.CopyTo(destFile)
'open the new document
System.Diagnostics.Process.Start(destFile)