Add String To File MD5 Hash In VB.NET?
I'm trying to calculate the hash of a file with MD5 and then add the filename to the data before i encrypt it with MD5. The filename should be added to the end of the file before encryption
So it looks something like md5(filedatabytes & filename)
Here's my code:
Code:
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
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Label4.Text = IntegrityCheck("D:\My Documents\My Games\FarmingSimulator2015\mods\weight6000.zip")
End Sub
End Class
But how do i add the filename before encrypting?
In this case it should add weight6000 before calculating the MD5.
Here is what i try to achieve written in PHP:
Code:
function getGiantsModMD5Hash($modFile)
{
$info = pathinfo($modFile);
// Add mod zip data
$fileContent = file_get_contents($modFile);
// Add basefile name string without extension
$fileContent .= basename($modFile, '.' . $info['extension']);
return md5($fileContent);
}
Re: Add String To File MD5 Hash In VB.NET?
I haven't tested this and haven't done much hashing myself, but it seems to me that you could use an appropriate Encoding object and call GetBytes to convert the file name to a Byte array and then pass that when you call TransformFinalBlock.