Solved

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

Posted on 2010-09-13
5
1,821 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

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

User art_snob (http://www.experts-exchange.com/M_6114203.html) encountered strange behavior of Android Web browser on his Mobile Web site. It took a while to find the true cause. It happens so, that the Android Web browser (at least up to OS ver. 2.…
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…
This video discusses moving either the default database or any database to a new volume.
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

759 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now