Solved

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

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

Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Help with consolidating excel files using VB.net 2 29
location of a form 2 25
What are the simplest ways to create a Merge Sort? 3 29
Add a Condition in ASP Repeater 6 34
A quick way to get a menu to work on our website, is using the Menu control and assign it to a web.sitemap using SiteMapDataSource. Example of web.sitemap file: (CODE) Sample code to add to the page menu: (CODE) Running the application, we wi…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

828 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