Free Information Technology Magazines and eBooks

Monday, April 20, 2009

VB.NET: Check if file is tampered

There are times that we have to implement file tampering detection on some file that we receive to verify its authenticity. On this article I will try to show you how to do it in VB.NET

First we need the following namespaces for file handling and hash computation:


Imports System.IO
Imports System.Security.Cryptography


For Beginner's sake, here is the definition of Cryptography namespace:

System.Security.Cryptography namespace provides cryptographic services, including secure encoding and decoding of data, as well as many other operations, such as hashing, random number generation, and message authentication.



To continue the article, On your VB.NET Project, Add two textboxes that will handle both the original file and the file being compared. It should look like something below:

File tampering detection in VB.NET

Where:
1st File = Original File
2nd File = File being check if tampered

Then on the Test button, Put the following code:


Private Sub btnTest_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTest.Click
Dim myHash As HashAlgorithm

myHash = HashAlgorithm.Create()
'Check if there are selected files
If txt1stFile.Text <> String.Empty And txt2ndFile.Text <> String.Empty Then
'Open Original file using IO
Dim fs1 As New FileStream(txt1stFile.Text, FileMode.OpenOrCreate)
Dim fs1Bytes As Byte() = New Byte(fs1.Length) {}
fs1.Read(fs1Bytes, 0, fs1.Length)
Dim arr1() As Byte = myHash.ComputeHash(fs1Bytes)
fs1.Close()
'Open 2nd File (the file being check for tampering)
Dim fs2 As New FileStream(txt2ndFile.Text, FileMode.OpenOrCreate)
Dim fs2Bytes As Byte() = New Byte(fs2.Length) {}
fs2.Read(fs2Bytes, 0, fs2.Length)
Dim arr2() As Byte = myHash.ComputeHash(fs2Bytes)
fs2.Close()

'Compare using Bit Converter
If BitConverter.ToString(arr1) = BitConverter.ToString(arr2) Then
MessageBox.Show("The file is good.", "Hash Test")
Else
MessageBox.Show("The file was tampered.", "Hash Test")
End If

Else
MessageBox.Show("Please specify both 1st and 2nd files.", "Required Fields", MessageBoxButtons.OK)

End If
End Sub


To test if the function is working, try to edit the 2nd file using Text Editor then recompare it again. The application should tell you that the file has been tampered. The most important line on this code was:

Dim arr1() As Byte = myHash.ComputeHash(fs1Bytes)


The function ComputeHash returns Hash values that will use by the program to compare the two files. Using this method, you can compare large plain text files or binary files without converting it first to string.

You can download the full project including test files you can use at mediafire. You can use the test files on \testfiles folder, It contains plain text, xml and binary files.


0 comments: