How to md5 hash a file

I would like to open a file, generate an md5 hash and compare that hex hash value to a know good value. I have not been able to find an example of this nor the correct crypto package to use. Can anyone assist here?

I was finally able to put a function script together by combining a few different examples from the web. I am posting in case anyone need this in the future…As i am new to Katalon, I am happy to take suggestions on cleaning it up.

Steps are login, navigate to report, click export and file type, click download, confirm the file is downloaded, perform hash, compare hash.


import static com.kms.katalon.core.checkpoint.CheckpointFactory.findCheckpoint
import static com.kms.katalon.core.testcase.TestCaseFactory.findTestCase
import static com.kms.katalon.core.testdata.TestDataFactory.findTestData
import static com.kms.katalon.core.testobject.ObjectRepository.findTestObject
import static com.kms.katalon.core.testobject.ObjectRepository.findWindowsObject
import com.kms.katalon.core.checkpoint.Checkpoint as Checkpoint
import com.kms.katalon.core.cucumber.keyword.CucumberBuiltinKeywords as CucumberKW
import com.kms.katalon.core.mobile.keyword.MobileBuiltInKeywords as Mobile
import com.kms.katalon.core.model.FailureHandling as FailureHandling
import com.kms.katalon.core.testcase.TestCase as TestCase
import com.kms.katalon.core.testdata.TestData as TestData
import com.kms.katalon.core.testng.keyword.TestNGBuiltinKeywords as TestNGKW
import com.kms.katalon.core.testobject.TestObject as TestObject
import com.kms.katalon.core.webservice.keyword.WSBuiltInKeywords as WS
import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI
import com.kms.katalon.core.windows.keyword.WindowsBuiltinKeywords as Windows
import internal.GlobalVariable as GlobalVariable
import org.openqa.selenium.Keys as Keys
import com.kms.katalon.core.annotation.Keyword
import com.kms.katalon.core.util.KeywordUtil
import org.testng.Assert
import java.nio.file.Files
import java.nio.file.Paths
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.MessageDigest
import org.openqa.selenium.Keys as Keys
String home = System.getProperty(‘user.home’)
String userDownloads = new File(home + ‘/Downloads/’)

WebUI.openBrowser(’’)

WebUI.navigateToUrl(‘https://your url/’)

WebUI.click(findTestObject(‘Object Repository/input_Sign in_UserName’))

WebUI.setEncryptedText(findTestObject(‘Object Repository/input_Email_Password’), your passwd’)

WebUI.setText(findTestObject(‘Object Repository/input_Sign in_UserName’), ‘your uid’)

WebUI.click(findTestObject('Object Repository/label_I agree to the terms '))

WebUI.click(findTestObject(‘Object Repository/span_Sign in’))

WebUI.click(findTestObject(‘Object Repository/button_Toggle left-side menu’))

WebUI.click(findTestObject(‘Object Repository/a_Example report’))

WebUI.delay(20)

WebUI.click(findTestObject(‘Object Repository/button_Export’))

WebUI.click(findTestObject(‘Object Repository/button_PDF’))

WebUI.click(findTestObject(‘Object Repository/button_Download’))

WebUI.click(findTestObject(‘Object Repository/a_Download’))

WebUI.click(findTestObject(‘Object Repository/span_useridt’))

WebUI.click(findTestObject(‘Object Repository/a_Sign Out’))

isFileDownloaded(userDownloads, “example report.pdf”)
WebUI.closeBrowser()

public boolean isFileDownloaded(String downloadPath, String fileName) {
System.out.println(downloadPath)
System.out.println(fileName)
File dir = new File(downloadPath);
File[] dirContents = dir.listFiles();
System.out.println(dirContents)
String lastAttempt = ‘’;
if (dirContents.length > 0) {
for (int i = 0; i < dirContents.length; i++) {
if (dirContents[i].getName().equals(fileName)) {
// File has been found, it can now be deleted:
// dirContents[i].delete();
GFG.main()
KeywordUtil.markPassed(fileName + ’ exist in ’ + downloadPath )
return true;
}
lastAttempt = dirContents[i].getName().equals(fileName);
}
if (lastAttempt != fileName) {
KeywordUtil.markFailed(fileName + ’ does not exist in ’ + downloadPath)
return false;
}
}
return false;
}

public class GFG {

   // this method gives a NoSuchAlgorithmException in case
   // we pass a string which dosen't have any hashing
   // algorithm in its correspondence
  
   public static void main(String[] args)
	   throws IOException, NoSuchAlgorithmException
   {

	   // create a file object referencing any file from
	   // the system of which checksum is to be generated
	   File file = new File("C:\\Users\\userid\\Downloads\\example report.pdf");

	   // instantiate a MessageDigest Object by passing
	   // string "MD5" this means that this object will use
	   // MD5 hashing algorithm to generate the checksum
	   MessageDigest mdigest = MessageDigest.getInstance("MD5");

	   // Get the checksum
	   String checksum = checksum(mdigest, file);

	   // print out the checksum
	   System.out.println(checksum);
   }

   // this method return the complete  hash of the file
   // passed
   private static String checksum(MessageDigest digest,
								  File file)
	   throws IOException
   {
	   // Get file input stream for reading the file
	   // content
	   FileInputStream fis = new FileInputStream(file);

	   // Create byte array to read data in chunks
	   byte[] byteArray = new byte[1024];
	   int bytesCount = 0;

	   // read the data from file and update that data in
	   // the message digest
	   while ((bytesCount = fis.read(byteArray)) != -1)
	   {
		   digest.update(byteArray, 0, bytesCount);
	   };

	   // close the input stream
	   fis.close();

	   // store the bytes returned by the digest() method
	   byte[] bytes = digest.digest();

	   // this array of bytes has bytes in decimal format
	   // so we need to convert it into hexadecimal format

	   // for this we create an object of StringBuilder
	   // since it allows us to update the string i.e. its
	   // mutable
	   StringBuilder sb = new StringBuilder();
	  
	   // loop through the bytes array
	   for (int i = 0; i < bytes.length; i++) {
		  
		   // the following line converts the decimal into
		   // hexadecimal format and appends that to the
		   // StringBuilder object
		   sb.append(Integer
				   .toString((bytes[i] & 0xff) + 0x100, 16)
				   .substring(1));
	   }

	   // we can return the complete hash
	  // return sb.toString();
	   
	  // finally, we compare the generated hash to the known good hash. The good hash was generated by completing thee export steps manually and generating the md5
	   //with notepad++
	   String knownHash = '8d67db2892f7e2f036628f318bbc0527'
	   if (sb.toString().equals(knownHash)) {
		   KeywordUtil.markPassed('Hash match')
		   return true;
	   }
	   if (sb.toString() != knownHash) {
		   KeywordUtil.markFailed('Hash does not match')
		   return false;
	   }
   }

}