programming.torensma.net: Code Snippets

Compute hash of a file

Computing the hash value of a file is quite strait forward. I use the routine below. It opens the file, specifies the hash-algorithm to use and returns the hash of the file. If you rather use MD5 hashes, just change hashAlgorithm into MD5CryptoServiceProvider.

Public Function ComputeFileHash(ByVal fileName As String) As String

  Dim hashAlgorithm As New System.Security.Cryptography.SHA1CryptoServiceProvider()

  Using stmcheck As System.IO.FileStream = System.IO.File.OpenRead(fileName)

    Dim hash As Byte() = hashAlgorithm.ComputeHash(stmcheck)
    Dim computed As String = BitConverter.ToString(hash).Replace("-", "")

    Return computed

  End Using

End Function

SHA1 hashes typically produce 160-bit (20 bytes) messages (16 bytes for MD5). If you want to store the hash value in a database table, make sure the field is wide enough to prevent data from getting truncated. By default the ComputeHash method returns the bytes separated by a hyphen (-). To save space I opted to remove these.

You can follow any responses to this entry through the RSS 2.0 feed.