Solved

How to hash (MD5 or SHA1) a file with VB.NET

Posted on 2010-09-13
5
1,937 Views
Last Modified: 2012-05-10
Hi experts..
I have a VB.NET application which imports a few csv files into a database nightly..
I need to ascertain if the file has changed from the previous nights import before I decide to import it or not.

I thought the easiest way would be to hash the file and store this hash in a table.
Then, each subsequent nightly import, I would simply hash the file, compare it with the hash of the file uploaded the previous night, if the hash's match, do nothing, if the hash's are different, perform the import..

So, can anyone poiont me in the right direction for hashing a file with VB.NET please??

Thanks in advance.

D
0
Comment
Question by:jcm4101
  • 3
  • 2
5 Comments
 
LVL 29

Accepted Solution

by:
nffvrxqgrcfqvvc earned 500 total points
ID: 33668882
You can use HashAlgorithm Class, I wrote this class for when I need to calculate hash in either MD5 or SHA1 here you go.
The example defaults to MD5 but just change this line to use SHA1CryptoServiceProvider for SHA1 hash instead.
hashAlg = New MD5CryptoServiceProvider ' or New SHA1CryptoServiceProvider

Imports System.Security.Cryptography
Imports System.IO

Public Class FileChecksum
    Private Const BUF_SIZE As Integer = 65536
    ''' <summary>
    ''' Returns the file integrity checksum hash, otherwise an empty string.
    ''' </summary>
    Public Shared Function IntegrityCheck(ByVal filePath As String) As String
        Dim dataBuffer(BUF_SIZE - 1) As Byte
        Dim dataBufferDummy(BUF_SIZE - 1) As Byte
        Dim dataBytesRead As Integer = 0
        Dim hashResult As String = String.Empty
        Dim hashAlg As HashAlgorithm = Nothing
        Dim fs As FileStream = Nothing

        Try
            hashAlg = New MD5CryptoServiceProvider ' or New SHA1CryptoServiceProvider
            fs = New FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, BUF_SIZE)
            Do
                dataBytesRead = fs.Read(dataBuffer, 0, BUF_SIZE)
                hashAlg.TransformBlock(dataBuffer, 0, dataBytesRead, dataBufferDummy, 0)
            Loop Until dataBytesRead = 0
            hashAlg.TransformFinalBlock(dataBuffer, 0, 0)
            hashResult = BitConverter.ToString(hashAlg.Hash).Replace("-", "").ToLower
        Catch ex As IOException
            MsgBox(ex.Message, MsgBoxStyle.Critical, "IntegrityCheck")
        Catch ex As UnauthorizedAccessException
            MsgBox(ex.Message, MsgBoxStyle.Critical, "IntegrityCheck")
        Finally
            If Not fs Is Nothing Then
                fs.Close()
                fs.Dispose()
                fs = Nothing
            End If
            If Not hashAlg Is Nothing Then
                hashAlg.Clear() 'Dispose()
                hashAlg = Nothing
            End If
        End Try
        Return hashResult
    End Function

End Class

Open in new window

0
 

Author Closing Comment

by:jcm4101
ID: 33668977
Excellent work...
Thanks for the quick and complete solution.

D
0
 

Author Comment

by:jcm4101
ID: 33669031
Actually, I'm a bit confused...

What's the correct way to call this class??

Ta
0
 
LVL 29

Expert Comment

by:nffvrxqgrcfqvvc
ID: 33669056
Whoops I forgot to show that part :(
It's basically just one shared method wrapped in class so it's similiar in respect to a module where you don't need to create an instance.
In the example below I used hashed the windows calculator on Windows 7: calc.exe MD5: 4884da7754823b44ccc2b2106f21146e
 

Debug.Print(FileChecksum.IntegrityCheck("c:\windows\system32\calc.exe"))

Open in new window

0
 

Author Comment

by:jcm4101
ID: 33669084
Thanks  a lot..

Just sussed it out myself too  :-)

Greatly appreciated.

D
0

Featured Post

Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It’s quite interesting for me as I worked with Excel using vb.net for some time. Here are some topics which I know want to share with others whom this might help. First of all if you are working with Excel then you need to Download the Following …
Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question