VB.NET – Calculate CRC32 Hash from File

VB.NET – Calculate CRC32 Hash from File.

Public Function GetCRC32(ByVal sFileName As String) As String
        Dim FS As FileStream = New FileStream(sFileName, FileMode.Open, FileAccess.Read, FileShare.Read, 8192)
        Dim CRC32Result As Integer = &HFFFFFFFF
        Dim Buffer(4096) As Byte
        Dim ReadSize As Integer = 4096
        Dim Count As Integer = FS.Read(Buffer, 0, ReadSize)
        Dim CRC32Table(256) As Integer
        Dim DWPolynomial As Integer = &HEDB88320
        Dim DWCRC As Integer
        Dim i As Integer, j As Integer, n As Integer

        'Create CRC32 Table
        For i = 0 To 255
            DWCRC = i
            For j = 8 To 1 Step -1
                If (DWCRC And 1) Then
                    DWCRC = ((DWCRC And &HFFFFFFFE) \ 2&) And &H7FFFFFFF
                    DWCRC = DWCRC Xor DWPolynomial
                    DWCRC = ((DWCRC And &HFFFFFFFE) \ 2&) And &H7FFFFFFF
                End If
            Next j
            CRC32Table(i) = DWCRC
        Next i

        'Calcualting CRC32 Hash
        Do While (Count > 0)
            For i = 0 To Count - 1
                n = (CRC32Result And &HFF) Xor Buffer(i)
                CRC32Result = ((CRC32Result And &HFFFFFF00) \ &H100) And &HFFFFFF
                CRC32Result = CRC32Result Xor CRC32Table(n)
            Next i
            Count = FS.Read(Buffer, 0, ReadSize)
        Return Hex(Not (CRC32Result))
    Catch ex As Exception
        Return ""
    End Try
End Function
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s