Click here to Skip to main content
15,900,816 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi everyone im so confused i have this code :

VB
Dim LimitReached As Boolean = Me.InvokeIfRequired(Function() ProgressBar1.Value = ProgressBar1.Maximum)

'Keep looping until limit is reached.
While Not LimitReached

    'InvokeIfRequired() can take multiple lines.
    Me.InvokeIfRequired(
    Sub()
        ProgressBar1.Maximum = ListBox1.Items.Count.ToString() 'Calling ToString() is much better than Conversions.ToString().
        total.Text = ListBox1.Items.Count.ToString()
    End Sub) 'End of InvokeIfRequired().

    'Check if the limit is reached.
    LimitReached = Me.InvokeIfRequired(Function() ProgressBar1.Value = ProgressBar1.Maximum)

    If Not LimitReached Then

        Me.InvokeIfRequired(
        Sub()
            Try
                ListBox1.SelectedIndex = ListBox1.SelectedIndex + 1
                Label1.Text = ListBox1.SelectedItem.ToString
            Catch ex As Exception
            End Try
        End Sub)

        Try

            Me.InvokeIfRequired(
        Sub()
            ProgressBar1.Increment(1)
            detected.Text = Quarantine.ListBox2.Items.Count.ToString() 'Again, use .ToString(), not Conversions.ToString().
            Label5.Text = String.Format("{0:F2}%", ((ProgressBar1.Value / ProgressBar1.Maximum) * 100))
            files.Text = ProgressBar1.Value.ToString()
        End Sub)


            Dim SHA256 As New SHA256CryptoServiceProvider 'Shortened to "As New" instead of "As ... = New ..."

            'IMPORTANT: Wrap all streams in "Using .../End Using". This will ensure that the stream is closed and the file handle is released.
            Using f As New FileStream(ListBox1.SelectedItem, FileMode.Open, FileAccess.Read, FileShare.Read, 8192) 'Again, shortened to "As New".

                'REMOVED: You were setting "f = New FileStream..." two times. Not a good thing to do.
                SHA256.ComputeHash(f)
                Dim hash As Byte() = SHA256.Hash
                Dim buff As New StringBuilder '"As New".
                'This line is irrelevant: "Dim hashByte As Byte".
                For Each hashByte As Byte In hash
                    buff.Append(String.Format("{0:X2}", hashByte))
                Next


                Dim MyFilesList As String() = Directory.GetFiles(Application.StartupPath & "\Database\Sigs\Sha1\", "*.txt")
                Dim FoundedSearch As New List(Of String)()
                For Each filename As String In MyFilesList
                    Dim textFile As String = File.ReadAllText(filename)
                    If textFile.Contains(buff.ToString) Then
                        Me.InvokeIfRequired(Sub() f.Dispose())
                        Me.InvokeIfRequired(Sub() EncryptFile())
                        Me.InvokeIfRequired(Sub() Quarantine.ListBox2.Items.Add(ListBox1.SelectedItem()))
                        Me.InvokeIfRequired(Sub() WriteToLog("File Quarantined:" + ListBox1.SelectedItem))
                    End If
                Next

            End Using 'Close the FileStream.

        Catch ex As Exception
        End Try
    Else
        'REMOVED: "Timer1.Stop()" is no longer needed.

        Me.InvokeIfRequired(
        Sub()
            If CheckBox1.Checked = True Then
                System.Diagnostics.Process.Start("shutdown", "-s -t 00")
            Else
                ProgressBar1.Value = 0
                If ListBox1.Items.Count = 0 Then
                    If Form1.CheckBox1.Checked = True Then
                        full.CancelAsync()
                        quick.CancelAsync()
                        Critical.CancelAsync()
                        cust.CancelAsync()
                    End If
                Else
                    Form1.CheckBox1.Checked = False
                    Form1.CheckBox2.Checked = False
                    Form1.CheckBox3.Checked = False
                    Form1.CheckBox4.Checked = False
                    Quarantine.Label3.ForeColor = Color.DarkRed
                    Quarantine.Label2.ForeColor = Color.DarkRed
                    full.CancelAsync()
                    quick.CancelAsync()
                    Critical.CancelAsync()
                    cust.CancelAsync()

                End If
            End If
        End Sub) 'End of InvokeIfRequired().
    End If
    'Do some more background stuff...
End While


And
Dim SHA256 As New SHA256CryptoServiceProvider
was md5 and it worked and scanned a list of md5 hashes but now i want to do sha256 and i used a list of sha256 hahses and it doesnt detect the file(the file is the same hash i checked using virus total)

What I have tried:

as you can see above i've tried changing it to sha256 the only thing i should need to change but nope not working. :-(
Posted
Updated 4-Nov-17 11:32am
v3

1 solution

Ummm....yeah, EVERYTHING is wrong with that code. I'm not trying to be rude, but what you posted is a fine example of something that someone coming in behind you to maintain would burn to the ground and rewrite from scratch.

Methods should do one thing and do that one thing is a short amount of code. You have to go through a ton of crap just to switch out the hashing algorithm. That's bad.

You should have a method that just takes a filepath and returns a byte array, the hash result. That way, its easy to change out the hashing algorithm and it's all done in a single place.

I've done something similar, but I've written a class that wraps a filepath and exposes a couple of methods that generates multiple hashes for that file. It just so happens that it generates both an MD5 and an SHA1 hash for the file. Something like this, (of course, this is C#. I'm too lazy to convert it to VB.NET):
C#
public class FileHash
{
    public string Filepath { get; private set; }

    public string Filename
    {
        get
        {
            return Path.GetFileName(Filepath);
        }
    }

    public byte[] MD5Hash { get; private set; }

    public byte[] SHA1Hash { get; private set; }

    private FileHash()
    {
    }

    public FileHash(string filepath)
    {
        if (string.IsNullOrWhiteSpace(filepath))
        {
            throw new ArgumentNullException(nameof(filepath));
        }

        Filepath = filepath;
    }

    public void ComputeHashes()
    {
        using (MD5CryptoServiceProvider md5Provider = new MD5CryptoServiceProvider())
        {
            MD5Hash = GenerateHash(md5Provider, Filepath);
        }

        using (SHA1CryptoServiceProvider sha1Provider = new SHA1CryptoServiceProvider())
        {
            SHA1Hash = GenerateHash(sha1Provider, Filepath);
        }
    }

    private byte[] GenerateHash(HashAlgorithm cryptoProvider, string filepath)
    {
        // Check the input parameters to make sure we get
        // something useful.
        if (cryptoProvider == null)
        {
            throw new ArgumentNullException(nameof(cryptoProvider));
        }

        if (string.IsNullOrWhiteSpace(filepath) || !File.Exists(filepath))
        {
            throw new ArgumentNullException(nameof(filepath));
        }

        // We need something to hold the results we
        // get back from the alsogirthm.
        byte[] result;

        // Open the file and hash it using the provided
        // algorithm.
        using (FileStream stream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            result = cryptoProvider.ComputeHash(stream);
        }

        // Return the result.
        return result;
    }
}

This is the stripped down version of the class. I removed all the Async stuff for clarity.
 
Share this answer
 
Comments
OfficalCodexPH 5-Nov-17 5:02am    
cheers mate :-)
OfficalCodexPH 5-Nov-17 5:19am    
Dude ive tried but im really unsure of how to implement this into my code with the list box ect?
Dave Kreskowiak 5-Nov-17 8:30am    
I can't write your code for you. I just don't have the time. This wasn't meant to be a copy'n'paste into your code, but as an example of how to encapsulate specific functionality and avoid some of that mess you posted.

The simple version is to create an instance of this class, passing in a filepath, and then call ComputeHashes on it.
Hide   Copy Code
    Dim hash As New FileHash(filepath)    hash.ComputeHashes

Once the method returns, you get the values of the hashes from the two properties:
Hide   Copy Code
    whatever = hash.MD5Hash
Maciej Los 5-Nov-17 7:01am    
5ed!
OfficalCodexPH 5-Nov-17 14:22pm    
dont worry dude i wrote it myself and made it work

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900